Java Program to sort array elements in descending order

Java Program to sort array elements in descending order

In this tutorial you will be learning writing java program to sort the given array in descending order.

For example:

Suppose we have an array arr = [2, 1, 4, 2, 5, 8]

output will be [1, 2, 2, 4, 5, 8]

Program 1 : Sort array in descending order using Java

import java.util.*;
public class Main{
    public static void main (String[]args){
        Scanner sc = new Scanner (System.in);
    
        //Taking array size and array element as input
        System.out.println ("Enter the size of array: ");
        int size = sc.nextInt();
        int arr[] = new int[size];
        int i,j,temp;
        for ( i = 0; i < size; i++){
	        System.out.print("Please give value for index " + i + " : ");
	        arr[i] = sc.nextInt();
        }
        
        //logic to sort array in descending order
        for (i = 0; i < size; ++i) 
        {
            for (j = i + 1; j < size; ++j) 
            {
                if (arr[i] < arr[j]) 
                {
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        System.out.println ("Array sorted in descending order is ");
        for (i = 0; i < size; ++i)
            System.out.print(arr[i] + " ");
    }
}

Output

Enter the size of array: 
5
Please give value for index 0 : 3
Please give value for index 1 : 1
Please give value for index 2 : 4
Please give value for index 3 : 2
Please give value for index 4 : 3
Array sorted in ascending order is 
4 3 3 2 1 

Program 2 : Java Program to sort array in descending order

import java.util.*;
public class Main{
    public static void main (String[]args){
        Scanner sc = new Scanner (System.in);
        //Taking array size and array element as input
        System.out.println ("Enter the size of array: ");
        int size = sc.nextInt();
        int arr[] = new int[size];
        int i,j,temp;
        for ( i = 0; i < size; i++){
	        System.out.print("Please give value for index " + i + " : ");
	        arr[i] = sc.nextInt();
        }
        //here first we are sorting the array in ascending order
        Arrays.sort(arr);
        
        //this logic is to reverse Array
        //after reversal, array will become sorted in descending order
        for (i = 0; i < size / 2; i++) {
            temp = arr[i];
            arr[i] = arr[size - i - 1];
            arr[size - i - 1] = temp;
        }
        System.out.println ("Array sorted in descending order is ");
        for (i = 0; i < size; ++i)
            System.out.print(arr[i] + " ");
    }
}

Output

Enter the size of array: 
6
Please give value for index 0 : 4
Please give value for index 1 : 7
Please give value for index 2 : 9
Please give value for index 3 : 3
Please give value for index 4 : 2
Please give value for index 5 : 7
Array sorted in descending order is 
9 7 7 4 3 2