ZetCode

C# Selection Sort

last modified November 6, 2026

In this article we implement the selection sort algorithm in C#. We sort numbers and strings, write a generic version that accepts a comparer, show why selection sort is not stable, and compare its speed with Array.Sort.

Sorting is arranging the elements of a collection in a specific order, for instance from the smallest to the largest. A sorting algorithm is the sequence of steps that produces this order.

Selection sort algorithm

Selection sort divides the array into a sorted part at the beginning and an unsorted part after it. In each step, it scans the unsorted part, selects its smallest element, and swaps it with the first unsorted element. The sorted part grows by one element per step.

PropertyValue
Best, average and worst caseO(n²) comparisons
Swapsat most n - 1
Extra memoryO(1), sorts in place
Stableno

The algorithm always makes the same number of comparisons, even for sorted input. Its advantage is the small number of writes: each element moves at most once. This matters only where writing is much more expensive than reading.

C# selection sort example

The first example sorts an array of integers in ascending order.

Program.cs
int[] nums = [64, 25, 12, 22, 11, 90, 3];

SelectionSort(nums);
Console.WriteLine(string.Join(" ", nums));

static void SelectionSort(int[] arr)
{
    int n = arr.Length;

    for (int i = 0; i < n - 1; i++)
    {
        int min = i;

        for (int j = i + 1; j < n; j++)
        {
            if (arr[j] < arr[min])
            {
                min = j;
            }
        }

        if (min != i)
        {
            (arr[i], arr[min]) = (arr[min], arr[i]);
        }
    }
}

The method sorts the array in place.

int min = i;

for (int j = i + 1; j < n; j++)
{
    if (arr[j] < arr[min])
    {
        min = j;
    }
}

We remember the index of the smallest element found so far. The inner loop scans the unsorted part of the array, which starts at index i.

if (min != i)
{
    (arr[i], arr[min]) = (arr[min], arr[i]);
}

The smallest element is swapped with the first unsorted element. If it is already in place, no swap is needed. After n - 1 steps, the last element is necessarily the largest one.

$ dotnet run
3 11 12 22 25 64 90

Selection sort step by step

The next example prints the array after each step. The sorted part is shown in square brackets.

Program.cs
int[] nums = [29, 10, 14, 37, 13, 5];

SelectionSort(nums);

static void SelectionSort(int[] arr)
{
    int n = arr.Length;
    int swaps = 0;

    for (int i = 0; i < n - 1; i++)
    {
        int min = i;

        for (int j = i + 1; j < n; j++)
        {
            if (arr[j] < arr[min]) min = j;
        }

        if (min != i)
        {
            (arr[i], arr[min]) = (arr[min], arr[i]);
            swaps++;
        }

        string sorted = string.Join(" ", arr[..(i + 1)]);
        string rest = string.Join(" ", arr[(i + 1)..]);
        Console.WriteLine($"step {i + 1}: [{sorted}] {rest}");
    }

    Console.WriteLine($"swaps: {swaps}");
}

We count the swaps and print the sorted and the unsorted part of the array.

string sorted = string.Join(" ", arr[..(i + 1)]);
string rest = string.Join(" ", arr[(i + 1)..]);

The range operator creates copies of the two parts of the array.

In step 2, the smallest unsorted element 10 is already in place, so the algorithm does not swap anything. Six elements are sorted in five steps with four swaps.

$ dotnet run
step 1: [5] 10 14 37 13 29
step 2: [5 10] 14 37 13 29
step 3: [5 10 13] 37 14 29
step 4: [5 10 13 14] 37 29
step 5: [5 10 13 14 29] 37
swaps: 4

Generic selection sort

The generic version takes an optional IComparer<T>. Without a comparer, it uses the default ordering of the type.

Program.cs
string[] words = ["kiwi", "apple", "banana", "cherry", "fig"];

SelectionSort(words);
Console.WriteLine(string.Join(" ", words));

SelectionSort(words, Comparer<string>.Create((a, b) => b.CompareTo(a)));
Console.WriteLine(string.Join(" ", words));

int[] nums = [5, -2, 9, 0, 3];

SelectionSort(nums, Comparer<int>.Create((a, b) => b.CompareTo(a)));
Console.WriteLine(string.Join(" ", nums));

static void SelectionSort<T>(T[] arr, IComparer<T>? comparer = null)
{
    comparer ??= Comparer<T>.Default;

    for (int i = 0; i < arr.Length - 1; i++)
    {
        int min = i;

        for (int j = i + 1; j < arr.Length; j++)
        {
            if (comparer.Compare(arr[j], arr[min]) < 0) min = j;
        }

        if (min != i)
        {
            (arr[i], arr[min]) = (arr[min], arr[i]);
        }
    }
}

The method sorts strings and integers in ascending and descending order.

comparer ??= Comparer<T>.Default;

The null-coalescing assignment falls back to Comparer<T>.Default, which uses the IComparable<T> implementation of the type.

SelectionSort(words, Comparer<string>.Create((a, b) => b.CompareTo(a)));

The Comparer<T>.Create method turns a lambda into an IComparer<T>. Comparing b with a gives the descending order.

$ dotnet run
apple banana cherry fig kiwi
kiwi fig cherry banana apple
9 5 3 0 -2

Selection sort is not stable

A sorting algorithm is stable if elements with equal keys keep their original relative order. The long-distance swaps of selection sort can move an element past another element with the same key.

Program.cs
Card[] cards = [new(4, "hearts"), new(2, "spades"), new(4, "clubs"), new(1, "diamonds")];

SelectionSort(cards, (a, b) => a.Rank.CompareTo(b.Rank));

foreach (var card in cards)
{
    Console.WriteLine(card);
}

static void SelectionSort<T>(T[] arr, Comparison<T> compare)
{
    for (int i = 0; i < arr.Length - 1; i++)
    {
        int min = i;

        for (int j = i + 1; j < arr.Length; j++)
        {
            if (compare(arr[j], arr[min]) < 0) min = j;
        }

        if (min != i)
        {
            (arr[i], arr[min]) = (arr[min], arr[i]);
        }
    }
}

record Card(int Rank, string Suit);

We sort playing cards by their rank. The four of hearts comes before the four of clubs in the input.

In the first step, the one of diamonds is swapped with the four of hearts, which jumps to the end of the array, past the four of clubs. In the output, the two fours are in the opposite order. To get a stable sort, use an algorithm such as insertion sort or merge sort, or LINQ OrderBy.

$ dotnet run
Card { Rank = 1, Suit = diamonds }
Card { Rank = 2, Suit = spades }
Card { Rank = 4, Suit = clubs }
Card { Rank = 4, Suit = hearts }

Selection sort vs Array.Sort

In the last example, we sort 20,000 random integers with selection sort and with Array.Sort.

Program.cs
#:property PublishAot=false

using System.Diagnostics;

var rnd = new Random(17);
int[] data = [.. Enumerable.Range(0, 20_000).Select(_ => rnd.Next(1_000_000))];

int[] a = [.. data];
var sw = Stopwatch.StartNew();
long swaps = SelectionSort(a);
Console.WriteLine($"Selection sort: {sw.ElapsedMilliseconds} ms, {swaps} swaps");

sw.Restart();
swaps = SelectionSort(a);
Console.WriteLine($"Selection sort, sorted input: {sw.ElapsedMilliseconds} ms, {swaps} swaps");

int[] b = [.. data];
sw.Restart();
Array.Sort(b);
Console.WriteLine($"Array.Sort: {sw.Elapsed.TotalMilliseconds:F3} ms");

Console.WriteLine($"Same result: {a.SequenceEqual(b)}");

static long SelectionSort(int[] arr)
{
    long swaps = 0;

    for (int i = 0; i < arr.Length - 1; i++)
    {
        int min = i;

        for (int j = i + 1; j < arr.Length; j++)
        {
            if (arr[j] < arr[min]) min = j;
        }

        if (min != i)
        {
            (arr[i], arr[min]) = (arr[min], arr[i]);
            swaps++;
        }
    }

    return swaps;
}

The method returns the number of swaps. We call it once on the random data and once more on the already sorted result.

#:property PublishAot=false

File-based apps are published with Native AOT by default. The directive turns this off, so the release build does not pull in the AOT compiler package.

We run the program in the Release configuration. Selection sort takes the same time for random and for sorted input, because it always scans the whole unsorted part. For sorted input it makes no swaps; for random data it makes almost n swaps. Array.Sort is about a hundred times faster.

$ dotnet run -c Release benchmark.cs
Selection sort: 103 ms, 19986 swaps
Selection sort, sorted input: 102 ms, 0 swaps
Array.Sort: 1.024 ms
Same result: True

Source

Comparer<T> class

In this article we have implemented the selection sort algorithm in C#.

Other sorting algorithms in C#:

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.