Selection Sort in Descending Order in Java

In this blog post, we'll explore the mechanism of sorting an array in descending order using Selection Sort in Java.

Java Program for Selection Sort in Descending Order

public class SelectionSortDescending {

    public static void main(String[] args) {
        // Initialize a sample array of numbers
        int[] numbers = {64, 34, 25, 12, 22, 11, 90};

        // Sort the array using Selection Sort
        selectionSort(numbers);

        // Display the sorted array
        System.out.println("Sorted array in descending order:");
        for (int num : numbers) {
            System.out.print(num + " ");
        }
    }

    /**
     * Perform selection sort on the given array in descending order.
     *
     * @param arr The array to be sorted.
     */
    public static void selectionSort(int[] arr) {
        int n = arr.length;

        // One by one move the boundary of the unsorted sub-array
        for (int i = 0; i < n - 1; i++) {
            // Find the maximum element in the unsorted array
            int max_idx = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] > arr[max_idx]) {
                    max_idx = j;
                }
            }

            // Swap the found maximum element with the first element of the sub-array
            int temp = arr[max_idx];
            arr[max_idx] = arr[i];
            arr[i] = temp;
        }
    }
}

Output:

Sorted array in descending order:
90 64 34 25 22 12 11

Step-by-Step Explanation:

Initialization: Our sample array of integers named numbers is initialized. This array will be sorted in descending order. 

Selection Sort Mechanism: The selectionSort function carries out the sorting. Its sole purpose is to sort the provided array in descending order using the Selection Sort algorithm. 

Finding the Maximum: For every iteration, the largest element in the unsorted section of the array is located. This is accomplished by iterating through the array and comparing elements. 

Swapping: After pinpointing the largest element in the unsorted portion, it's swapped with the first element of this section. With each iteration of the outer loop, the boundary between the sorted and unsorted sections shifts, leading to the expansion of the sorted section. 

Displaying the Output: Once sorting is completed, the numbers array is looped through, and every number (now in descending order) is printed out. 

The Selection Sort algorithm, while straightforward, isn't typically the best choice for extensive lists. Its primary value is in serving as an introductory algorithm for newcomers to computer science. With this guide, you should now have a firm grasp of how to adapt Selection Sort for descending order, particularly in Java. Keep coding and exploring!

Comments