Java Program to sort an array in descending order


In this program, You will learn how to sort an array in descending order in java.


Array list in descending order: 60 50 40 30 20 10

Example: How to sort an array in descending order in java.

import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        Scanner s = new Scanner(System.in);
        int a[] = new int[10];
        int n;

        System.out.print("Enter size of an array:");
        n = s.nextInt();

        System.out.print("Enter array elements:");
        for (int i = 0; i < n; i++) {
            a[i] = s.nextInt();
        }

        for (int i = 0; i < n; i++) {
            for (int j = 1 + i; j < n; j++) {
                if (a[i] < a[j]) {
                    int temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }

        System.out.print("Array list in descending order:");
        for (int i = 0; i < n; i++) {
            System.out.print(" " + a[i]);
        }

    }
}

Output:

Enter size of an array:5
Enter array elements:10 20 30 40 50
Array list in descending order: 50 40 30 20 10

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.