Write a program to Sort an array in descending order using selection sort


This is a Java program that implements the selection sort algorithm to sort an array of integers in descending order.

The program initializes an array of integers named a with 10 elements. It then uses a while loop with an outer loop variable i to traverse the array from the beginning to the end. The inner loop, with a loop variable j, searches for the maximum value in the remaining unsorted portion of the array.

If the value of the element at index j is greater than the value of the element at index max, the program sets the value of max to j. Once the maximum value is found, the program swaps it with the element at the current index i.

This process repeats until the entire array is sorted in descending order. Finally, the program uses another while loop to display the sorted array.

Source Code

public class Descending_SelectionSort
{
	public static void main(String[] args)
	{
		int i = 0;
		int j = 0;
		int t = 0;
		int max = 0;
		int a[] = {2, 65, 23, 13, 18, 30, 46, 17, 52, 78};
 
		while(i < 10)
		{
			max = i;
			j = i + 1;
 
			while(j < 10)
			{
				if(a[j] > a[max])
				max = j;
				j = j + 1;
			}
 
			t = a[i];
			a[i] = a[max];
			a[max] = t;
 
			i = i + 1;
		}
 
		System.out.println("Sorted Array in Descending Order .. ");
		i = 0;
		while(i < 10)
		{
			System.out.print(a[i] + " ");
			i = i + 1;
		}
	}
}

Output

Sorted Array in Descending Order ..
78 65 52 46 30 23 18 17 13 2

Example Programs