Straight Selection Sort in C#

Description: Basic implementation of Selection Sort for C#. 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: .NET, Visual Studio 2010, Windows 7
Language: C#
// Basic selection sort with optional sorting direction flag (asc by default).
// Sorts given array passed by reference and sorts it.

public static void SelectionSort(ref int[] arNumbers, bool sortDesc = false) {
    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