Straight Selection Sort in Java

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 1.7, Windows 7
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;
        }
    }
}

Submitted: February 15, 2013

Return to the snippets listing