ADVERTISEMENT
ADVERTISEMENT

Java program to sort an array in descending order

In this java program, we are going to learn how to read an integer array and sort array in descending order?
Submitted by IncludeHelp, on November 01, 2017

Given an array of integers and print array in descending order using java program.

Example:

    Input:  
    55, 25, 36, 99, 12, 9, 55, 88, 66, 47  
    
    Output: 
    99, 88, 66, 55, 55, 47, 36, 25, 12, 9

In this java program, we are reading total number of elements (N) first, and then according the user input (value of N)/total number of elements, we are reading the elements. Then sorting elements of array in descending order and then printing the elements which are sorted in descending order.

Program

import java.util.Scanner;

public class ExSortInDescending {
  public static void main(String[] args) {
    int n, temp;
    //scanner class object creation
    Scanner s = new Scanner(System.in);

    //input total number of elements
    System.out.print("Enter number of elements you want : ");
    n = s.nextInt();

    //integer arrar declarations
    int a[] = new int[n];

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

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

    //print sorted array
    System.out.println("Descending Order:");
    for (int i = 0; i < n; i++) {
      System.out.println(a[i]);
    }
  }
}

Output

Enter number of elements you want : 10
Enter all the elements:
55
25
36
99
12
9
55
88
66
47
Descending Order:
99
88
66
55
55
47
36
25
12
9

Java Array Programs »


ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.