Sort an array in Java
I'm trying to make a program that consists of an array of 10 integers which all has a random value, so far so good.
However, now I need to sort them in order from lowest to highest value and then print it onto the screen, how would I go about doing so?
(Sorry for having so much code for a program that small, I ain't that good with loops, just started working with Java)
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));
System.out.println(array[0] +" " + array[1] +" " + array[2] +" " + array[3]
+" " + array[4] +" " + array[5]+" " + array[6]+" " + array[7]+" "
+ array[8]+" " + array[9] );
}
Solution 1:
Loops are also very useful to learn about, esp When using arrays,
int[] array = new int[10];
Random rand = new Random();
for (int i = 0; i < array.length; i++)
array[i] = rand.nextInt(100) + 1;
Arrays.sort(array);
System.out.println(Arrays.toString(array));
// in reverse order
for (int i = array.length - 1; i >= 0; i--)
System.out.print(array[i] + " ");
System.out.println();
Solution 2:
Add the Line before println and your array gets sorted
Arrays.sort( array );
Solution 3:
It may help you understand loops by implementing yourself. See Bubble sort is easy to understand:
public void bubbleSort(int[] array) {
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < array.length - j; i++) {
if (array[i] > array[i + 1]) {
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
}
Of course, you should not use it in production as there are better performing algorithms for large lists such as QuickSort or MergeSort which are implemented by Arrays.sort(array)
Solution 4:
Take a look at Arrays.sort()
Solution 5:
I was lazy and added the loops
import java.util.Arrays;
public class Sort {
public static void main(String args[])
{
int [] array = new int[10];
for ( int i = 0 ; i < array.length ; i++ ) {
array[i] = ((int)(Math.random()*100+1));
}
Arrays.sort( array );
for ( int i = 0 ; i < array.length ; i++ ) {
System.out.println(array[i]);
}
}
}
Your array has a length of 10. You need one variable (i
) which takes the values from 0
to 9
.
for ( int i = 0 ; i < array.length ; i++ )
^ ^ ^
| | ------ increment ( i = i + 1 )
| |
| +-------------------------- repeat as long i < 10
+------------------------------------------ start value of i
Arrays.sort( array );
Is a library methods that sorts arrays.