In this tutorial you will learn about the Java Program to sort the elements of an array in descending order and its application with practical example.
In this tutorial, we will learn to create a Java Program to sort the elements of an array in descending order using java programming.
Prerequisites
Before starting with this tutorial, we assume that you are best aware of the following Java programming concepts:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
Sorting in a an array[]
Sorting elements means to arrange elements within the array in a certain specific order. either Ascending(increasing) or descending(decreasing) order.
Java Program to sort the elements of an array in ascending order
In this program we will take size of an array and sort the elements of an array using nested for loop. We would first declared and initialized the required variables. Next, we will sort the elements in an array. Lets have a look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
//java program to print array in decending order import java.util.Scanner; public class Descending { public static void main(String[] args) { int number, temp; Scanner s = new Scanner(System.in); System.out.print("Enter elements you want in array:"); number = s.nextInt(); int a[] = new int[number]; System.out.println("Enter all the elements:"); for (int i = 0; i < number; i++) { a[i] = s.nextInt(); } for (int i = 0; i < number; i++) { for (int j = i + 1; j < number; 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 < number - 1; i++) { System.out.print(a[i] + ","); } System.out.print(a[number - 1]); } } |
Output
Sorted elements in an array.
In the above program, we have first declared and initialized a set variables required in the program.
- arr[]= it will hold array values
- number = it will hold length of an array.
- i = for iteration.
- temp = it will hold temporary value of an array.
After declaring variables we initiate values in an array[]
Elements will be sorted in Descending order .As shown in the image below.
Algorithm to sort array in descending order.
- Start the algo
- Declare an array[].
- Taking size and element of an array from user.
- Declared a temp variable to store the elements for swapping.
- Here first for loop will hold the elements and traverse through all the elements.
- Second for loop to compare with the remaining elements.
- Sort the elements by comparing.
- Display the updated array.
- Stop
The above program shows sort an array in descending order using for loops .