Sort Array Elements in Descending Order using Java
Programming is always a fun and creative task. The more creative you can think the better programmer you will become. However, programming isn’t always about solving problems sometimes there’s also a fun aspect to it which makes it way more satisfying. If you are a programmer then you might have already played with patterns, strings, etc multiple times. Well, it’s also like that you are already familiar with arrays and numbers, so what about sorting array elements in descending order. So in today’s article, we will Sort Array Elements in Descending Order using Java. With the help of this program, you will be able to sort an array with the largest element at first and the smallest one at the last. Practising these types of questions also helps to get an upper edge in Competitive Programming.
So open up your IDE and let’s get started real quick. Once you understand the logic practice this program on your own to make your brain work in a problem-solving way. This is a pretty easy question so you might not get asked in an interview but practising this question will make your grip more firm in the Java language.
Also Read: Print Duplicate Characters in String Using Java
What’s The Approach?
There are two ways by which we can sort array elements in descending order, we’re going to look at the second method. The first method is the basic and slowest while the second method is extremely easy and blazing fast.
We will use the sort()
method of java.util.Arrays
class. This method takes input parameters as an array and Collections.reverseOrder()
method.
And at last, we will convert the sorted array into a string by using the Arrays.toString()
method and will print the same.
Java Program To Sort Array Elements in Descending Order
Input Parameters in the array :
1, 2, 3, 4, 5
// Java program to sort the elements in descending order import java.util.*; class TechDecodeTutorials { 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