- How to sort an Array in descending order in Java? Example Tutorial
- How to sort Object Array in Descending Order
- How to sort a Primitive Array in Reverse Order
- Java Program to Sort an Array in Decreasing Order
- Java Sort Array – How to Reverse an Array in Ascending or Descending Order with Arrays.sort()
- How to Sort an Array in Ascending Order in Java Using Arrays.sort()
- How to Sort an Array in Descending Order in Java Using Collections.reverseOrder()
- Summary
How to sort an Array in descending order in Java? Example Tutorial
Sorting an array is one of the common tasks in Programming and you have many algorithms to sort an array, like QuickSort, MergeSort which provides O(NLogN) time performance, and Bucket Sort, Counting Sort, and Radix Sort algorithms which can even sort some array in O(N) time. But, you hardly need to code these algorithms by hand when it comes to writing real code. The Programming language you will use already has tried and tested implementation for those algorithms and that’s what you will learn in this article. In Java Programming language, it’s easy to sort an array, you just need to call the Arrays.sort() method with a Comparator which can sort the array in the order you want but it highly depends upon which type of object is stored in the array.
For example, you can sort an object array in decreasing or reverse order, just provide a Comparator with the opposite order. You can even use Collections.reverseOrder() if you want to sort an array in the decreasing order, which returns a reverse Comparator to sort objects in the order opposite of their natural ordering defined by the compareTo() method.
Unfortunately, for a primitive array, there is no direct way to sort in descending order. The Arrays.sort() method which is used to sort a primitive array in Java doesn’t accept a boolean to sort the primitive array in reverse order.
You might have seen the error «no suitable method found for sort(int[],comparator)» which occurs when programmers try to call the Arrays.sort() method by passing reverse Comparator defined bythe Collection.reverseOrder() method .
That will work fine with an Integer array but will not work with an int array. The only way to sort a primitive array in descending order is first to sort the array in ascending order and then reverse the array in place as shown here. This is also true for two-dimensional primitive arrays.
Btw, if you are new to Java Programming and not familiar with common Java API and classes like Comparator, Arrays, and Integer then I suggest you first go through a comprehensive course like The Complete Java Masterclass on Udemy which will teach you all these and much more in quick time. It’s also the most up-to-date course in Java.
How to sort Object Array in Descending Order
First, let’s see the example of sorting an object array into ascending order. Then we’ll see how to sort a primitive array in descending order. In order to sort a reference type array-like String array, Integer array or Employee array, you need to pass the Array.sort() method a reverse Comparator.
Fortunately, you don’t need to code it yourself, you can use Collections.reverseOrder(Comparator comp) to get a reverse order Comparator. Just pass your Comparator to this method and it will return the opposite order Comparator.
If you are using a Comparator method to sort in the natural order, you can also use the overloaded Collection.reverseOrder() method. It returns a Comparator which sorts in the opposite of natural order. In fact, this is the one you will be using most of the time.
Here is an example of sorting Integer arrays in descending order:
Integer[] cubes = new Integer[] < 8, 27, 64, 125, 256 >; Arrays.sort(cubes, Collections.reverseOrder());
Now the cubes array will be , you can see the order is reversed and elements are sorted in decreasing order .
Sometimes, you use your own customized Comparator like a comparator we have used to sort Employee by their salary. If you are using that one then you need to call the Array.sort() method as follows
Arrays.sort(emp[], Collections.sort(SALARY_CMP));
where SALARY_CPM is the Comparator that orders employees by their salary. You can see the Java Fundamentals: The Java Language course on Pluralsight to learn more about Java and how to do basic stuff like sorting and searching in Java.
How to sort a Primitive Array in Reverse Order
Now, let’s see how to sort a primitive array like int[] , long[] , float[], or char[] in descending order. As I told you before, there are no Arrays.sort() method which can sort the array in the reverse order. Many programmers make the mistake of calling the above Array.sort() method as follows:
int[] squares = < 4, 25, 9, 36, 49 >; Arrays.sort(squares, Collections.reverseOrder());
This is a compile-time error «The method sort(int[]) in the type Arrays is not applicable for the arguments (int[], Comparator)» because there is no such method in the java.util.Arrays class.
The only way to sort a primitive array in descending order is first to sort it in ascending order and then reverse the array in place as shown on the link.
Since in-place reversal is an efficient algorithm and doesn’t require extra memory, you can use it to sort and reverse large arrays as well.
You can also see a comprehensive course on data structure and algorithms like Data Structures and Algorithms: Deep Dive Using Java to learn more about efficient sorting algorithms like O(n) sorting algorithms like Bucket sort and Counting Sort in Java.
Java Program to Sort an Array in Decreasing Order
Here is a complete Java program to sort an object array and a primitive array in the reverse order in Java. As I told it’s easy to sort a reference array to decreasing order because you can supply a reverse Comparator by using Collections.reverseOrder() method, but it’s tricky to sort the primitive array in reverse order.
The only way to achieve that is first by sorting the array in increasing order and then reverse the array in place and that is what I have done in this example.
I have used the Arrays.sort() method to sort a primitive array in ascending order and then written a reverse() method to reverse the array in place.
Since there are eight primitive types in Java, you need to write separate reverse methods to reverse a byte array, long array, or float array.
import java.util.Arrays; import java.util.Collections; /* * Java Program to sort the array in descending order. * Object array can be sorted in reverse order by using * Array.sort(array, Comparator) method but primitive * array e.g. int[] or char[] can only be sorted * in ascending order. For opposite order, just * reverse the array. * */ public class ArraySorter < public static void main(String[] args) < // sorting Integer array in descending order Integer[] cubes = new Integer[] < 8, 27, 64, 125, 256 >; System.out.println("Integer array before sorting : " + Arrays.toString(cubes)); System.out.println("sorting array in descending order"); Arrays.sort(cubes, Collections.reverseOrder()); System.out.println("array after sorted in reverse order: " + Arrays.toString(cubes)); // sorting primitive array int[] in descending order int[] squares = < 4, 25, 9, 36, 49 >; System.out.println("int[] array before sorting : " + Arrays.toString(squares)); System.out.println("sorting array in ascending order"); Arrays.sort(squares, Collections.reverseOrder()); System.out.println("reversing array in place"); reverse(squares); System.out.println("Sorted array in descending order : " + Arrays.toString(squares)); > /** * reverse given array in place * * @param input */ public static void reverse(int[] input) < int last = input.length - 1; int middle = input.length / 2; for (int i = 0; i = middle; i++) < int temp = input[i]; input[i] = input[last - i]; input[last - i] = temp; > > > Output Integer array before sorting : [8, 27, 64, 125, 256] sorting array in descending order array after sorted in reverse order: [256, 125, 64, 27, 8] int[] array before sorting : [4, 25, 9, 36, 49] sorting an array in ascending order reversing array in place Sorted array in descending order : [49, 36, 25, 9, 4]
That’s all about how to sort an array in descending order in Java. You can use a reverse Comparator or Collections.reverseOrder() method to sort an object array in descending order e.g. String array, Integer array, or Double array.
The Arrays.sort() method is overloaded to accept a Comparator, which can also be a reverse Comparator. Now, to sort a primitive array in decreasing order, there is no direct way.
You first need to sort it in ascending or normal order and then reverse the array in place. The in-place algorithm is an efficient way to reverse an array and doesn’t require extra memory, so it can also be used to reverse a large array.
- How to declare and initialize a two-dimensional array in Java? (solution)
- How to convert an Array to String in Java? (solution)
- My favorite free courses to learn data Structure in-depth (FreeCodeCamp)
- How to test if an array contains a value in Java? (solution)
- 22 Array concepts Interview Questions in Java? (answer)
- How to print elements of an array in Java? (example)
- 100+ Data Structure Coding Problems from Interviews (questions)
- What is the difference between array and ArrayList in Java? (answer)
- How to loop over an array in Java? (solution)
- How to find duplicate elements in a Java array? (answer)
- How to remove duplicate objects from an array in Java? (answer)
- 50+ Data Structure and Algorithms Problems from Interviews (questions)
- Iterative PreOrder traversal in a binary tree (solution)
- How to count the number of leaf nodes in a given binary tree in Java? (solution)
- 10 Free Data Structure and Algorithm Courses for Programmers (courses)
- 10 Free Courses to Learn Java Programming (courses)
Thanks for reading this article so far. If you like this Java Array tutorial and sorting array in descending order then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment.
P. S. — If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check these free Data structure courses from Udemy, Coursera, and Pluralsight
Java Sort Array – How to Reverse an Array in Ascending or Descending Order with Arrays.sort()
Ihechikara Vincent Abba
In Java, you use arrays to store a collection of variables (with the same data type) in a single variable.
In many cases, the values stored in an array appear in a random order. Using the Arrays class in Java, you have access to various methods you can use to manipulate arrays.
One of the methods we’ll be using from the Arrays class is the sort() method which sorts an array in ascending order.
We’ll also see how to sort an array in descending order using the reverseOrder() method from the Collections class in Java.
How to Sort an Array in Ascending Order in Java Using Arrays.sort()
In this section, we’ll see an example on how we can use the sort() method to sort an array in ascending order.
import java.util.Arrays; class ArraySort < public static void main(String[] args) < int[] arr = < 5, 2, 1, 8, 10 >; Arrays.sort(arr); for (int values : arr) < System.out.print(values + ", "); // 1, 2, 5, 8, 10, >> >
The first thing we did in the example above was to import the Arrays class: import java.util.Arrays; . This give us access to all the methods of the Arrays class.
We then created an array with numbers in a random order: int[] arr = < 5, 2, 1, 8, 10 >; .
In order to sort this array in ascending order, we passed in the array as parameter to the sort() method: Arrays.sort(arr); .
Note that the Arrays class was written first before accessing the sort() method using dot notation.
Lastly, we looped through and printed the array in the console. The result was a sorted array: 1, 2, 5, 8, 10 .
In the next section, we’ll talk about sorting an array in descending order.
How to Sort an Array in Descending Order in Java Using Collections.reverseOrder()
To sort an array in descending order, we use the reverseOrder() which we can access from the Collections class.
We’ll still make use of Arrays.sort(); , but in this example, it’ll take in two parameters – the array to be sorted and Collections.reverseOrder() .
import java.util.Arrays; import java.util.Collections; class ArraySort < public static void main(String[] args) < Integer[] arr = < 5, 2, 1, 8, 10 >; Arrays.sort(arr, Collections.reverseOrder()); for (int values : arr) < System.out.print(values + ", "); // 10, 8, 5, 2, 1, >> >
First things first, we imported the Arrays and Collections classes because we’ll be making use the methods provided by the classes.
We then created an array of numbers in random order: Integer[] arr = < 5, 2, 1, 8, 10 >; . You’ll notice that we used Integer[] instead of int[] like we did in the last example – the latter would throw an error.
To sort the array in descending order, we did this: Arrays.sort(arr, Collections.reverseOrder()); .
The first parameter is the array arr which will be sorted in ascending order. The second parameter – Collections.reverseOrder() – will then reverse the order of the sorted array so it is arranged in descending order.
When looped through and printed, the array would look like this: 10, 8, 5, 2, 1 .
Summary
In this article, we talked about sorting arrays in Java. Arrays can be sorted in ascending or descending order.
We can sort arrays in ascending order using the sort() method which can be accessed from the Arrays class. The sort() method takes in the array to be sorted as a parameter.
To sort an array in descending order, we used the reverseOrder() method provided by the Collections class. This is passed in as a second parameter in the sort() method so that the sorted array can be rearranged in descending order.