Sorting by ascending order:
You can sort an array using Arrays.sort method. This method sorts the array by
ascending order.
Now, if you want to sort the array in reverse (descending order). You have to
use the Collections method: reverse(List<T> list).
You can achieve this as follows:
Create an a List. The List extends class Collections by which you can use to do stuff.
Loop and add the array elements to the List you created.
You can either sort the array and reverse it or do it in one line.
Example:
int[] arr = {2, 1, 9, 6, 4};
sortArr(arr);
sortArrRev(arr);
Output:
[1, 2, 4, 6, 9]
[9, 6, 4, 2, 1]
/* Sort by ascending. */ public static void sortArr(int[] arr) { ArrayList al = new ArrayList(); Arrays.sort(arr); for (int i = 0; i < arr.length; i++) { al.add(arr[i]); } System.out.println(al); } /* Sort by descending. */ public static void sortArrRev(int[] arr) { List al = new ArrayList(); for (int i = 0; i < arr.length; i++) { al.add(arr[i]); } Collections.sort(al, Collections.reverseOrder()); System.out.println(al); }
Or you can sort an array using Arrays.sort class,
a utility for java arrays.
Example:
This program returns the difference between max and min value in an
array.