Selection Sort(Descending) in Java

Selection sort in descending order is a sorting algorithm that repeatedly selects the maximum element from the unsorted portion of the array and places it at the end of the sorted portion. This process continues until the entire array is sorted in descending order, with the largest element at the beginning and the smallest at the end.

JAVA PROGRAMMING

Raki Adhikary

1/12/20231 min read

import java.util.*;

public class SelectionSortDescending {

public static void main(String args[]) {

int size;

Scanner scanner = new Scanner(System.in);

System.out.println("Enter the size of the array:");

size = scanner.nextInt();

int array[] = new int[size];

int i, j, maxIndex, temp;

/* Taking input in the array */

for (i = 0; i < size; i++) {

System.out.println("Enter element at index " + i + ":");

array[i] = scanner.nextInt();

}

/* Selection Sorting the array in descending order */

for (i = 0; i < size - 1; i++) {

maxIndex = i;

for (j = i + 1; j < size; j++) {

if (array[j] > array[maxIndex]) {

// Finding the maximum element in the unsorted part of the array

maxIndex = j;

}

}

// Swapping the maximum element with the current element

temp = array[maxIndex];

array[maxIndex] = array[i];

array[i] = temp;

}

/* Displaying the sorted Array */

System.out.println("The sorted Array in descending order is:");

for (i = 0; i < size; i++)

System.out.print(array[i] + " ");

scanner.close();

}

}

Your Code is here