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 sort the given array in descending order in Java. A few of them are listed below.
- Using Collections.reverseOrder() method
- Using Sorting and reversing
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
import java.util.*;
class GFG {
public static void main(String[] args)
{
Integer array[] = { 1 , 2 , 3 , 4 , 5 };
Arrays.sort(array, Collections.reverseOrder());
System.out.println(Arrays.toString(array));
}
}
|
Time Complexity:O(N log N)
2. Using Sorting and Reversing
- Sort the given array.
- Reverse the sorted array.
Below is the implementation of the above approach:
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
int array[] = { 1 , 2 , 3 , 4 , 5 , 6 };
Arrays.sort(array);
reverse(array);
System.out.println(Arrays.toString(array));
}
public static void reverse( int [] array)
{
int n = array.length;
for ( int i = 0 ; i < n / 2 ; i++) {
int temp = array[i];
array[i] = array[n - i - 1 ];
array[n - i - 1 ] = temp;
}
}
}
|
Output
[6, 5, 4, 3, 2, 1]
Time Complexity: O(N2) Prior to Java 14, Arrays.sort(int[]) used dual pivot quick sort having worst case complexity of O(N2). From Java 14, Arrays.sort(int[]) used heap sort with worst case complexity of O(NlogN)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
16 May, 2023
Like Article
Save Article