Java array sorting in descending order
This Java example sort the array in a descending order without using any pre-define Java class method. We use for loop with conditional statement if-else to sort the array. The program output is also shown below.
Java program to sorting of array in descending order example
//User define Java program to sorting in descending order import java.util.Scanner; public class ArraySortingInDescendingOrder { static int n; public static void input1(int[] b){ Scanner uk = new Scanner(System.in); System.out.println("Enter " + n + " subject marks"); for(int l = 0; l < b.length; l++){ b[l] = uk.nextInt(); } } public static void sorting(int[] p){ int i,j; int temp; for(i=0; i<n; i++){ for(j=0; j< n-i-1; j++) { if (p[j] < p[j+1]){ temp = p[j]; p[j] = p[j+1]; p[j+1] = temp; } } } } public static void display(int[] b){ System.out.println("Sorted Marks:"); for(int l = 0; l< b.length; l++){ System.out.println(b[l]); } } public static void main(String[] args) { Scanner uk = new Scanner(System.in); System.out.println("Enter the number of element"); n = uk.nextInt(); int x[] = new int[n]; input1(x); sorting(x); display(x); } }
Output
Enter the number of element 3 Enter 3 subject marks 12 6 18 Sorted Marks: 18 12 6