Possible Duplicate:
Sort arrays of primitive types in descending order
Java : How to sort an array of floats in reverse order?
How do I reverse an int array in Java?
The following code will sort the array in ascending order :
int a[] = {30,7,9,20}; Arrays.sort(a); System.out.println(Arrays.toString(a));
I need to sort it in descending order. How do I use Comparator to do this?
Please help.
To sort an array in Java in descending order, you have to use the reverseOrder() method from the Collections class. The reverseOrder() method does not parse the array. Instead, it will merely reverse the natural ordering of the array.
A simple solution would be to use efficient sorting algorithms like Merge Sort, Quicksort, Heapsort, etc., that can solve this problem in O(n. log(n)) time, but those will not take advantage of the fact that there are many duplicated values in the array. A better approach is to use a counting sort.
It's not possible to sort an array of primitives in “descending” order using the Arrays. sort() and Collections. sort() method, since the comparator work on the Wrapper classes and objects instead of the primitives. For instance, the following code reverse sort an Integer array using the Arrays.
For primitive array types, you would have to write a reverse sort algorithm:
Alternatively, you can convert your int[]
to Integer[]
and write a comparator:
public class IntegerComparator implements Comparator<Integer> { @Override public int compare(Integer o1, Integer o2) { return o2.compareTo(o1); } }
or use Collections.reverseOrder()
since it only works on non-primitive array types.
and finally,
Integer[] a2 = convertPrimitiveArrayToBoxableTypeArray(a1); Arrays.sort(a2, new IntegerComparator()); // OR // Arrays.sort(a2, Collections.reverseOrder()); //Unbox the array to primitive type a1 = convertBoxableTypeArrayToPrimitiveTypeArray(a2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With