Java Program to Sort the Array Elements in Descending Order
Sort the given array in descending order, i.e., arrange the elements from largest to smallest.
Example:
Input: Array = {2, 6, 23, 98, 24, 35, 78} Output: [98, 78, 35, 24, 23, 6, 2] Input: Array = {1, 2, 3, 4, 5} Output: [5, 4, 3, 2, 1]
Sorting is a process of arranging items systematically. sort() is an inbuilt function from java.util.Arrays which is used to sort an array of elements in optimized complexity.
Approaches
There are numerous approaches to Sorting the given array in descending order in Java. A few of them are listed below.
- Using Collections.reverseOrder() method
- Using Sorting and reversing
1. Using Collections.reverseOrder() Method
Array elements can be sorted in descending order by passing in the array and Collections.reverseOrder() as parameters to Arrays.sort().
Note: One thing to keep in mind is that when sorting in descending order, Arrays.sort() does not accept an array of the primitive data type.
Implementation:
// Java Program to Sort the Elements in Descending Order
import java.util.*;
// Driver Class
class GFG {
// Main Method
public static void main(String[] args)
{
// Initializing the array
Integer array[] = { 1, 2, 3, 4, 5 };
// Sorting the array in descending order
Arrays.sort(array, Collections.reverseOrder());
// Printing the elements
System.out.println(Arrays.toString(array));
}
}
Output
[5, 4, 3, 2, 1]
Complexity of the above Method:
Time Complexity: O(N2) is the worst time Complexity of the method. O(N log N) is the average time complexity of the Sort method.
2. Using Sorting and Reversing
- Sort the given array.
- Reverse the sorted array.
Below is the implementation of the above approach:
// Java Program to Sort the Elements
// In Descending Order
import java.util.*;
// Driver Class
class GFG {
// Main Methods
public static void main(String[] args)
{
// Initializing the array
int array[] = { 1, 2, 3, 4, 5, 6 };
// Sorting the array in ascending order
Arrays.sort(array);
// Reversing the array
reverse(array);
// Printing the elements
System.out.println(Arrays.toString(array));
}
public static void reverse(int[] array)
{
// Length of the array
int n = array.length;
// Swapping the first half elements
// With last Half Elements
for (int i = 0; i < n / 2; i++) {
// Storing the first half elements temporarily
int temp = array[i];
// Assigning the first half
// to the last half
array[i] = array[n - i - 1];
// Assigning the last half
// to the first half
array[n - i - 1] = temp;
}
}
}
Output
[6, 5, 4, 3, 2, 1]
Complexity of the above Method:
Time Complexity: O(N2) , Arrays.sort(int[]) used dual pivot quick sort having worst case complexity of O(N2). And the average time complexity of Array.sort(int[]) is O(NlogN).