Home >Java >javaTutorial >How to Sort an Array in Reverse Order in Java?
Sorting an Array in Reverse
Many programming languages provide convenient functions for sorting arrays in ascending order. However, the question arises: Is there a similar approach for sorting arrays in descending order?
Java's Arrays Class
In Java, the Arrays class offers the sort() method for sorting arrays. However, this method lacks direct support for descending order. One option is to use a Comparator to define the reverse order of elements.
Using a Comparator
Arrays.sort() allows you to specify a Comparator to determine the sorting order. The Collections class provides the reverseOrder() method to create a Comparator that inverts the natural ordering.
Arrays.sort(a, Collections.reverseOrder());
This approach works for sorting arrays of objects, such as Integer arrays. However, it fails for primitive arrays, such as int arrays.
Alternative for Primitive Arrays
To sort primitive arrays in descending order, one must first sort them in ascending order using Arrays.sort() and then manually reverse the array elements.
Arrays.sort(a); for (int i = 0, j = a.length - 1; i < j; i++, j--) { int temp = a[i]; a[i] = a[j]; a[j] = temp; }
By employing these techniques, it is possible to sort an array in descending order, whether it contains objects or primitives.
The above is the detailed content of How to Sort an Array in Reverse Order in Java?. For more information, please follow other related articles on the PHP Chinese website!