JAVA program to sort the elements of an array in descending order
This JAVA program is to sort the elements of an array in descending order.
For example, if an array a consists of elements a={50,20,60,40} , then on sorting in descending order we would get a={20,40,50,60}.
Logic
We use two for loops, the outer for loop for traversing all the elements and the inner(nested) for loop for comparing the element with all of the inner elements and then performing swap operation
Dry Run of the Program
Take input array ‘a’ and no of elements(n) as 4
Let us take elements for array a={7,8,12,3}.
1st iteration for(i=0;i<n;i++) i.e. for(i=0;0<4;i++) – Outer for loop
1st iteration for(j=i+1;j<n;j++) i.e. for(j=1;1<4;j++) – Inner for loop
if(a[i]<a[j]) i.e. if(a[0]<a[1]) i.e. if(7<8) true
temp=a[i]; i.e. temp=a[0] i.e. temp=7
a[i]=a[j]; i.e. a[0]=a[1] i.e. a[0]=8
a[j]=temp; i.e. a[1]=7
So now are array is a={8,7,12,3}
2nd iteration for(j=i+1;j<n;j++) i.e. for(j=2;2<4;j++) – Inner for loop
if(a[i]<a[j]) i.e. if(a[0]<a[2]) i.e. if(8<12) true
temp=a[i]; i.e. temp=a[0] i.e. temp=12
a[i]=a[j]; i.e. a[0]=a[2] i.e. a[0]=12
a[j]=temp; i.e. a[2]=8
So now are array is a={12,7,8,3}
3rd iteration for(j=i+1;j<n;j++) i.e. for(j=3;3<4;j++) – Inner for loop
if(a[i]<a[j]) i.e. if(a[0]<a[3]) i.e. if(12<3) false
2nd iteration for(i=1;i<n;i++) i.e. for(i=1;1<4;i++) – Outer for loop
1st iteration for(j=i+1;j<n;j++) i.e. for(j=2;2<4;j++) – Inner for loop
if(a[i]<a[j]) i.e. if(a[1]<a[2]) i.e. if(7<8) true
temp=a[i]; i.e. temp=a[1] i.e. temp=7
a[i]=a[j]; i.e. a[1]=a[2] i.e. a[1]=8
a[j]=temp; i.e. a[2]=7
So now are array is a={12,8,7,3}
2nd iteration for(j=i+1;j<n;j++) i.e. for(j=3;3<4;j++) – Inner for loop
if(a[i]<a[j]) i.e. if(a[1]<a[3]) i.e. if(8<3) false
3rd iteration for(i=2;i<n;i++) i.e. for(i=2;2<4;i++) – Outer for loop
1st iteration for(j=i+1;j<n;j++) i.e. for(j=3;3<4;j++) – Inner for loop
if(a[i]<a[j]) i.e. if(a[2]<a[3]) i.e. if(7<3) false
Hence we have sorted the elements in descending order a={12,8,7,3}.
Program
import java.util.*; class arr8 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int i,j,n,temp; System.out.println("Enter the number of elements:") ; n = sc.nextInt(); int[] a = new int[n]; System.out.println("Enter the elements") ; for(i=0;i<n;i++) { a[i] = sc.nextInt(); } for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(a[i]<a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } System.out.println("Elements sorted in descending order are"); for(i=0;i<n;i++) { System.out.print(a[i]+" ") ; } } }