Open In App

Java Program to Sort the Elements of an Array in Descending Order

Last Updated : 14 Nov, 2024
Suggest changes
Share
Like Article
Like
Report

Here, we will sort the array in descending order to arrange elements from largest to smallest. The simple solution is to use Collections.reverseOrder() method. Another way is sorting in ascending order and reversing.

1. Using Collections.reverseOrder()

In this example, we will use Collections.reverseOrder() method along with the Arrays.sort() method to sort an array elements in descending order. This method requires the array to be of type Integer instead of int (primitive type).

Java
// Java Program to Sort the Elements in Descending Order // using Collections.reverseOrder() 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] 

Note: When sorting in descending order, Arrays.sort() does not accept an array of the primitive data type.

2. Using Sorting and Reversing

In this approach, first we sort the array in ascending order using Arrays.sort() method and then reverse the array to get the elements in descending order. This method works for primitive types like int.

Java
// Java Program to Sort the Elements in // Descending Order by Sorting and Reversing 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.


Next Article

Similar Reads