Home >Java >javaTutorial >How to Sort a Java Array in Descending Order?
Java Array Sort in Descending Order
An array sorting utility exists in the Arrays class to sort arrays in ascending order. However, there isn't a direct method to sort arrays in descending order.
Solution Using Comparator
To sort an array of objects in descending order, use the following code:
<code class="java">sort(T[] a, Comparator<? super T> c)</code>
<code class="java">Arrays.sort(a, Collections.reverseOrder());</code>
Solution for Primitive Arrays
For primitive arrays like int[], the above method won't work directly. Instead, follow these steps:
Sort the array in ascending order:
<code class="java">Arrays.sort(a);</code>
Reverse the sorted array in place:
<code class="java">reverseArray(a); private static void reverseArray(int[] arr) { for (int i = 0, j = arr.length - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }</code>
Example
<code class="java">public static void main(String[] args) { int[] arr = {5, 3, 1, 2, 4}; // Sort in descending order reverseArray(arr); // Print the sorted array for (int num : arr) { System.out.println(num); // 5, 4, 3, 2, 1 } }</code>
The above is the detailed content of How to Sort a Java Array in Descending Order?. For more information, please follow other related articles on the PHP Chinese website!