Straight Selection Sort

Description: Basic implementation of Selection Sort for Java. Provide the array to be sorted (passed by reference) and an optional directional sort flag to determine sort direction. This sort is generally better than bubblesort and good for small lists but inefficient for larger lists.
Tested Platform: Java SE 19, Windows 10
Language: Java
// Basic selection sort with sorting direction flag.
// Sorts given array passed by reference and sorts it.
// Parameter sortDesc: (true = descending / false = ascending)

public static void SelectionSort(int[] arNumbers, boolean sortDesc) {
    for (int i = 0; i < arNumbers.length - 1; i++) {
        int index = i;

        for (int j = i + 1; j < arNumbers.length; j++) {
            if (sortDesc) {
                if (arNumbers[j] > arNumbers[index]) { index = j; }
            }
            else  {
                if (arNumbers[j] < arNumbers[index]) { index = j; }
            }
        }

        // If current iteration index is different than
        // the minimum index found, swap them.
        if (index != i)  {
            int temp = arNumbers[i];
            arNumbers[i] = arNumbers[index];
            arNumbers[index] = temp;
        }
    }
}

Posted: March 20, 2023

Return to the snippets listing