Can someone please help me with this program? it is supposed to ask user to input ten integers which are part of an array and then output that array and then output the numbers in ascending and descending order in an array. can you repair this program? thanks.
import java.io.*;

public class Elements
{
static BufferedReader keyboard =
new BufferedReader(new InputStreamReader(System.in));


public static void main (String[] args) throws IOException
{
int[] input = new int[10];


System.out.println("Enter ten numbers each on a different line: ");


for(int i = 0; i < 10; i++)
{
input = Integer.parseInt(keyboard.readLine());
}
System.out.print("Your numbers are: ");
for (int i = 0; i < 9; i++)
{
System.out.print(input + ", ");
}
System.out.println(input[9] + ".");


int sort;
int unsort;
int Largest = -1;
int i;


for(sort = 0; sort < 10; sort++)
{
for(unsort = 0; unsort < 10; unsort++)
{
if(input[unsort] > Largest)
{
Largest = input[unsort];
i = unsort;
}
}
int[] NewAry = new int[10];
i = 0;
NewAry[sort] = Largest;
input = -1;
Largest = -1;
}
System.out.println("Your numbers in descending order are: " + NewAry[sort]);
}
}

Everything looks good except for the sorting code:

for(sort = 0; sort < 10; sort++)
{
for(unsort = 0; unsort < 10; unsort++)
{
if(input[unsort] > Largest)
{
Largest = input[unsort];
i = unsort;
}
}

It seems to me that you are trying to use Selection Sort. Selection Sort works by finding the max and putting it at the end. Finding the second max and putting it and the second last slot and so on. Since you must write it in descending and ascending it is easier to use bubble sort (you'll see why). The following code sorts ascending.

boolean sorted=false;


//while not sorted repeat
while(!sorted)
{
//assume its sorted
sorted = true;


//make a pass thru the array
for(int i =0; i < 9; i++)
{
//get two consecutive slots
int first = input;
int second = input[i+1];


//if out of order, swap
if(first > second)
{
input[i+1] = first;
input= second;


//KNOW ITS NOT SORTED!! so mark it as not sorted
sorted = false;
}
}
}

To sort descending, swap > with <. THATS IT!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.