Sort an Array in Descending Order using Java

[198 views]


Sorting an array:

Sorting an array process can be divided into two parts

  1. Ascending order: Smallest to largest
  2. Descending order: largest to smallest

Problem Statement:

Write a program to sort n number of array values in descending order.

Steps to solve this program:

  1. Take inputs.
  2. Using for loop array input taken from keyboard.
  3. Using nested for loop to adjust checking process.
  4. Using if and temp variable sort all array values in descending order.
  5. Using for loop display sorted array in descending order.

  1. Take Inputs
  2. Take inputs n, tamp an array for starting the program.

    int n, temp; Scanner s = new Scanner(System.in); System.out.print("Enter no. of elements you want in array:"); n = s.nextInt(); int a[] = new int[n];

  3. Take array inputs from keyboard:
  4. Using for loop take all array values from keyboard.

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

  5. Create nested for loop to generate iteration process:
  6. Using nested for loop conduct the array iteration process within the boundary where all array value present.

    for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) {//Swap Variable Values Logic...} }

  7. Swap array values in descending order:
  8. Using if statement and temp variable swap all array values in descending order.

    if (a[i] < a[j]) { temp = a[i]; a[i] = a[j]; a[j] = temp; }

  9. Display all array values in descending order:
  10. Display all array values using for loop in descending order

    System.out.print("Descending Order:"); for (int i = 0; i < n - 1; i++) { System.out.print(a[i] + ","); }

Full Java Code to Sort an Array in Descending Order:

import java.util.Scanner; public class Descending_Order { public static void main(String[] args) { int n, temp; Scanner s = new Scanner(System.in); System.out.print("Enter no. of elements you want in array:"); n = s.nextInt(); int a[] = new int[n]; System.out.println("Enter all the elements:"); for (int i = 0; i < n; i++) { a[i] = s.nextInt(); } 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; } } } System.out.print("Descending Order:"); for (int i = 0; i < n - 1; i++) { System.out.print(a[i] + ","); } System.out.print(a[n - 1]); } }

Console Output

Input: Enter all the elements: 2 3 5 1 4 Output: Descending Order:5,4,3,2,1
        

Don't Understand Algorithm and Flowchart? Learn quickly using our Expert's Notes



Want to get in-depth understanding of Algorithms?


Are You Good enough in Algorithms? Test it now?


Comments



Search
Recommended Deals End in










Java Interview Questions For Beginner Notes
Quiz for Learners
Online Games
Play 2048 Game Online and Relax.
Play 2048 Game Online

Search Tags