I have an array which consists of 10 random integers, what will be the fastest way to sort it from the largest to the smallest?
public class Main {
public static void main(String args[])
{
int [] array = new int[10];
array[0] = ((int)(Math.random()*100 1));
array[1] = ((int)(Math.random()*100 1));
array[2] = ((int)(Math.random()*100 1));
array[3] = ((int)(Math.random()*100 1));
array[4] = ((int)(Math.random()*100 1));
array[5] = ((int)(Math.random()*100 1));
array[6] = ((int)(Math.random()*100 1));
array[7] = ((int)(Math.random()*100 1));
array[8] = ((int)(Math.random()*100 1));
array[9] = ((int)(Math.random()*100 1));
for (int i = 0; i < 10; i ){
System.out.println(i ") " array[i]);
}
}
}
The only thing that comes to mind is bubble sort and the insertion sort
CodePudding user response:
You can use Arrays.sort(array);
CodePudding user response:
Although there are several ways to do this, this is one way. Read the comments in code:
int [] array = new int[10];
/* Generate an int[] Array with 10 elements consisting
of 10 elements holding a random number from 1 to 100
(duplicates allowed). */
System.out.println("Generated Array (Random Order):");
// Display the generated Array...
for (int i = 0; i < array.length; i ){
array[i] = ((int)(Math.random()*100 1));
System.out.printf("-) %-6d%n", (i 1), array[i]);
}
System.out.println();
// Sort the Array in Ascending Order 'first'!
System.out.println("Sorted Array (Ascending Order):");
Arrays.sort(array); // Sort in ascending order
// Display the sorted Array...
for (int i = 0; i < array.length; i ){
System.out.printf("-) %-6d%n",(i 1), array[i]);
}
System.out.println();
// Sort the Array in Ddescending Order 'second'!
System.out.println("Sorted Array (Descending Order):");
// Create a new int[] Array (arr[]) and place array[] into it in Descending order.
int[] arr = IntStream.rangeClosed(1, array.length).map(i -> array[array.length - i]).toArray();
// Copy the arr[] array into the array[] Array to overwrite it.
System.arraycopy(arr, 0, array, 0, arr.length);
// Display the sorted Array...
for (int i = 0; i < arr.length; i ){
System.out.printf("-) %-6d%n",(i 1), array[i]);
}
When the code is run, you could see something similar to this:
Generated Array (Random Order):
1) 80
2) 54
3) 100
4) 96
5) 71
6) 87
7) 22
8) 60
9) 67
10) 18
Sorted Array (Ascending Order):
1) 18
2) 22
3) 54
4) 60
5) 67
6) 71
7) 80
8) 87
9) 96
10) 100
Sorted Array (Descending Order):
1) 100
2) 96
3) 87
4) 80
5) 71
6) 67
7) 60
8) 54
9) 22
10) 18