# 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.

#### Take Inputs

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];

#### Take array inputs from keyboard:

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(); }

#### Create nested for loop to generate iteration process:

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...} }

#### Swap array values in descending order:

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; }

#### Display all array values in descending order:

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

## Want to get in-depth understanding of Algorithms?

#### Are You Good enough in Algorithms? Test it now?

##### Recommended Deals End in

Java Interview Questions For Beginner Notes