Sorting an array in descending order means arranging its elements from the largest value to the smallest value. In Java, this can be done using Collections.reverseOrder() with Arrays.sort() for wrapper classes, or by sorting a primitive array in ascending order and then reversing it.
- Descending order means arranging elements from largest to smallest.
- Collections.reverseOrder() can be used with Integer[].
Example:
Input: [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]Input: [10, 25, 5, 40, 15]
Output: [40, 25, 15, 10, 5]
Approaches to Sort the Elements of an Array
1. Using Collections.reverseOrder()
The Collections.reverseOrder() method returns a comparator that sorts elements in descending order. It can be used with Arrays.sort() for arrays of wrapper classes such as Integer[].
- Collections.reverseOrder() works with objects, not primitive types.
- Therefore, use Integer[] instead of int[].
import java.util.*;
class GFG {
public static void main(String[] args)
{
Integer a[] = { 1, 2, 3, 4, 5 };
// Sorting the array in descending order
Arrays.sort(a, Collections.reverseOrder());
System.out.println(Arrays.toString(a));
}
}
Output
[5, 4, 3, 2, 1]
Explanation: The Integer[] array is passed to Arrays.sort() along with Collections.reverseOrder(). The comparator changes the sorting order from the default ascending order to descending order.
2. Using Sorting and Reversing
Another approach is to first sort the array in ascending order using Arrays.sort() and then reverse the elements.
- Works with primitive arrays such as int[].
- Uses Arrays.sort() for ascending order.
import java.util.Arrays;
class GFG {
public static void main(String[] args) {
int a[] = { 1, 2, 3, 4, 5 };
// sort the array in ascending order
Arrays.sort(a);
// reverse the array
reverse(a);
System.out.println(Arrays.toString(a));
}
// method to reverse the array elements
public static void reverse(int[] a)
{
// length of an array
int n = a.length;
// swap the first half with the second half
for (int i = 0; i < n / 2; i++) {
// Store the first half elements temporarily
int t = a[i];
// Assign the first half
// to the last half
a[i] = a[n - i - 1];
// Assign the last half
// to the first half
a[n - i - 1] = t;
}
}
}
Output
[5, 4, 3, 2, 1]
Explanation: Here, we get the array elements in descending order for primitive arrays like int[], which is not possible with Collections.reverseOrder(), because this approach only works with arrays of non-primitive types.