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 l
Take a look at Arrays.sort()
You may use Arrays.sort() function.
sort() method is a java.util.Arrays class method.
Declaration : Arrays.sort(arrName)
Add the Line before println and your array gets sorted
Arrays.sort( array );
See below, it will give you sorted ascending and descending both
import java.util.Arrays;
import java.util.Collections;
public class SortTestArray {
/**
* Example method for sorting an Integer array
* in reverse & normal order.
*/
public void sortIntArrayReverseOrder() {
Integer[] arrayToSort = new Integer[] {
new Integer(48),
new Integer(5),
new Integer(89),
new Integer(80),
new Integer(81),
new Integer(23),
new Integer(45),
new Integer(16),
new Integer(2)
};
System.out.print("General Order is : ");
for (Integer i : arrayToSort) {
System.out.print(i.intValue() + " ");
}
Arrays.sort(arrayToSort);
System.out.print("\n\nAscending Order is : ");
for (Integer i : arrayToSort) {
System.out.print(i.intValue() + " ");
}
Arrays.sort(arrayToSort, Collections.reverseOrder());
System.out.print("\n\nDescinding Order is : ");
for (Integer i : arrayToSort) {
System.out.print(i.intValue() + " ");
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SortTestArray SortTestArray = new SortTestArray();
SortTestArray.sortIntArrayReverseOrder();
}}
Output will be
General Order is : 48 5 89 80 81 23 45 16 2
Ascending Order is : 2 5 16 23 45 48 80 81 89
Descinding Order is : 89 81 80 48 45 23 16 5 2
Note: You can use Math.ranodm instead of adding manual numbers. Let me know if I need to change the code...
Good Luck... Cheers!!!
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.