Home >>Java Programs >Java Program to sort the elements of an array in descending order
In this example, we will create a java program to sort the given array in descending order such that elements of the array will be arranged from largest to smallest. This can be achieved through two loops where the outer loop will select an element and the inner loop will allow us to compare the selected element with rest of the elements.
public class Main
{
public static void main(String[] args)
{
int [] arr = new int [] {5, 7, 8, 6, 1, 3, 9};
int temp = 0;
System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
for (int i = 0; i < arr.length; i++)
{
for (int j = i+1; j < arr.length; j++)
{
if(arr[i] < arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
System.out.println("Elements of array sorted in descending order: ");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
}