Updated on
Selection sort is a sorting algorithm that finds the smallest value in the unsorted part of an array and swaps it to the front of that part. In C#, it takes two nested loops and one swap per pass, and it makes the same number of comparisons whatever order the input is in.
Sorting is one of the most common problems that programmers solve while building applications. Let’s implement selection sort in C# and see how it performs when sorting arrays of various sizes.
Let’s start.Â
What Is Selection Sort?
The goal of the selection sort algorithm is to find the minimum value of the unsorted part of an array by iterating through each element. For each iteration, the algorithm compares the current minimum value with the current element. If the current value is smaller, it becomes the new minimum. When the pass ends, one swap moves that minimum to the front of the unsorted part. This process continues until the array is completely sorted.
NIST’s Dictionary of Algorithms and Data Structures puts the whole algorithm in one line: selection sort “repeatedly searches remaining items to find the least one and moves it to its final location”.
Let’s learn how selection sort in C# works and understand its time and space complexity.Â
How Does Selection Sort Work?
Let’s assume we have an array of five numbers we need to sort in ascending order:
int[] array = { 40, 10, 20, 30, 50 };
First, we find the minimum value from elements 0 to 4 (indexes) and place it at position 0. The minimum value is 10. Since 40 is currently in position 0, we swap it with 10:
10, 40, 20, 30, 50
Then, we check the elements 1 through 4 and place the smallest value at position 1. In this case, 20 is the minimum and we swap it with 40:
10, 20, 40, 30, 50
Next, we check positions 2 through 4 and set the minimum value (30) to position 2:
10, 20, 30, 40, 50
Finally, we check positions 3 and 4. 40 is already the smaller of the two, so it stays where it is, and the array is sorted:
10, 20, 30, 40, 50
Five elements need four passes. Once the first four values are in place, the largest one is the only value left, so the last position needs no pass of its own.

Selection sort on our five-element array: each pass moves the smallest remaining value to the front of the unsorted part.
Let’s learn how to implement Selection Sort in C#.Â
How to Implement Selection Sort in C#?
To implement selection sort in C#, we need two nested for loops, an index that remembers where the smallest value is, and a temporary variable for the swap.
The outer loop picks the position we want to fill, starting at index 0. The inner loop scans every element to the right of it and keeps the index of the smallest value it meets in smallestVal.
When the inner loop finishes, we swap the value at smallestVal with the value at the current position. That position now holds its final value, and the outer loop moves one step to the right.
An array of n elements needs n - 1 passes. Each pass makes exactly one swap, so the method makes n - 1 swaps in total. When the smallest value is already in place, the swap writes it back where it was.
The method sorts the array in place and returns the same array instance it was given.
First, we are going to define an array property NumArray in a Selection class of a new console app, that we are going to use to implement selection sort:Â
public int[] NumArray { get; set; } = [];
As the next step, we are going to create a SortArray method in the same class that iterates through the NumArray and sorts it in place:
public int[] SortArray()
{
var arrayLength = NumArray.Length;
for (int i = 0; i < arrayLength - 1; i++)
{
var smallestVal = i;
for (int j = i + 1; j < arrayLength; j++)
{
if (NumArray[j] < NumArray[smallestVal])
{
smallestVal = j;
}
}
var tempVar = NumArray[smallestVal];
NumArray[smallestVal] = NumArray[i];
NumArray[i] = tempVar;
}
return NumArray;
}
We can see that the algorithm uses two nested loops during the sorting process. We define two variables (tempVar and smallestVal) that hold values during the sorting process. As the outer loop iterates, smallestVal holds the current position of the array while the inner loop compares the current minimum value to the rest of the elements.Â
If the value of the array element is smaller than the current minimum value, smallestVal moves to that element. The swap happens once per pass, after the inner loop ends. This process stops when the outer loop hits its arrayLength - 1 limit.
In a test method of an MSTest project that references our app, we can go ahead to verify that the method returns a sorted array:Â
var array = new int[] { 73, 57, 49, 99, 133, 20, 1 };
var expected = new int[] { 1, 20, 49, 57, 73, 99, 133 };
var sortFunction = new Selection();
sortFunction.NumArray = array;
var sortedArray = sortFunction.SortArray();
Assert.IsNotNull(sortedArray);
CollectionAssert.AreEqual(expected, sortedArray);
What Is the Time and Space Complexity of Selection Sort?
Selection sort runs in O(N²) time in the best, average and worst case, and it needs O(1) extra space.
The time comes from the comparisons. Every pass scans the whole unsorted part, so our SortArray() method makes n(n − 1) / 2 comparisons whatever order the input is in. For 2,000 elements, that is 1,999,000 comparisons on random, sorted and reversed input alike.
The algorithm sorts in place, and the only extra storage is a few local variables, such as the smallestVal index and the tempVar variable that holds a value during the swap.
Swaps are where selection sort is cheap: at most n − 1, one per pass. On the same 2,000 random numbers, bubble sort made 1,000,748 swaps, while our method moved values in 1,991 of its 1,999 passes.
Selection sort is not stable. A swap can jump a value over an equal one, so equal values may change their order.
Best Case Complexity: it occurs when we need to sort a sorted array. The algorithm still performs every comparison, but each pass finds its minimum already in place, so no value changes position. The complexity stays O(N²).
Average Case Complexity: this scenario occurs when the elements are in random order. The algorithm performs the same comparisons and moves a value in almost every pass, so the complexity is O(N²).
Worst Case Complexity: assuming we have a list of numbers that are in descending order and we need to sort them in ascending order, the algorithm makes the same number of comparisons again, O(N²). It moves fewer values than on random data, though. Each early swap puts two values in their final places at once, so 2,000 descending numbers need only 1,000 swaps that change anything.
Advantages of Using Selection Sort
Selection sort is ideal for sorting small arrays. As the length of the array increases, the time taken to sort it grows quadratically, as the algorithm has a time complexity of O(N²).
We can use this algorithm when the cost of swapping values matters. For example, if swapping those values takes a lot of computing resources, selection sort keeps that cost low, because it makes only one swap per pass.
Ideal for situations where the cost of writing to a disk space matters. For example, a flash disk with no extra space could work with this algorithm, because it sorts in place and makes at most n − 1 swaps, as opposed to a sorting algorithm such as bubble sort that makes O(N²) swaps.
Disadvantages of Using Selection Sort
We should not use selection sort in a sorted array, as it would still perform O(N²) comparisons. In such a scenario, the optimized version of bubble sort stops after one pass, and insertion sort also finishes in linear time.
Selection sort becomes inefficient as the size of the array grows. Using this algorithm in CPU-intensive applications could reduce their performance.Â
Selection sort is also not stable. Let’s take three items where the first two share the key 2: (2, a), (2, b), (1, c). The first pass swaps (1, c) to the front, and (2, a) lands at the end, behind (2, b). When the order of equal keys matters, LINQ’s OrderBy() is the safer choice, because it keeps equal keys in their original order, and we cover it in our article on sorting with LINQ.
Selection Sort Algorithm Performance in C#
Let’s verify that the selection sort algorithm has a time complexity of O(N²) by using performance benchmarks with BenchmarkDotNet to test how long the algorithm takes to sort an array.
To kickstart this process, we are going to define a method in our Selection class that generates random numbers and adds them to an array with a specific length:
public static int[] AddRandomElements(int size)
{
var array = new int[size];
var rand = new Random();
var maxNum = 10000;
for (int i = 0; i < size; i++)
array[i] = rand.Next(maxNum + 1);
return array;
}
The AddRandomElements method takes the length of the array as its input. Using the inbuilt Random class, we generate random numbers from 0 to 10,000 that we’re going to put into the array.
To simulate a scenario where we have an array that is in order, we are going to define a method AddSortedElements in the same class that generates a sequence of elements:
public static int[] AddSortedElements(int size)
{
var array = new int[size];
for (int i = 0; i < size; i++)
array[i] = i;
return array;
}
BenchmarkDotNet times a benchmark by calling it many times, and our SortArray() sorts the array it gets in place. Give every call the same array, and from the second call on, the “random” case sorts numbers that are already in order, so the random and sorted rows end up measuring the same thing.
That is why the class below never sorts its generated array directly. Every call first copies it into _work:
public class SelectionBenchmarks
{
private readonly Selection _selection = new();
private int[] _source = [];
private int[] _work = [];
[Params(200, 2_000, 20_000)]
public int Size { get; set; }
[Params("Random", "Sorted")]
public string Input { get; set; } = "Random";
[GlobalSetup]
public void Setup()
{
_source = Input == "Random"
? Selection.AddRandomElements(Size)
: Selection.AddSortedElements(Size);
_work = new int[Size];
}
[Benchmark]
public int[] SortArray()
{
_source.CopyTo(_work, 0);
_selection.NumArray = _work;
return _selection.SortArray();
}
}
Setup() fills _source with random or sorted numbers once per Size and Input pair, before any timing starts. The copy is O(N) work, which is negligible next to an O(N²) sort.
The class goes in its own file in our console app. We add the BenchmarkDotNet package to the app, start the class file with using BenchmarkDotNet.Attributes;, and call BenchmarkRunner.Run<SelectionBenchmarks>(); from its Program.cs, after using BenchmarkDotNet.Running;. Let’s run it in Release mode and look at the results:
| Method | Size | Input | Mean | Error | StdDev | |---------- |------ |------- |--------------:|-----------:|-----------:| | SortArray | 200 | Random | 12.53 us | 0.036 us | 0.028 us | | SortArray | 200 | Sorted | 11.00 us | 0.022 us | 0.019 us | | SortArray | 2000 | Random | 1,087.34 us | 7.098 us | 6.292 us | | SortArray | 2000 | Sorted | 1,028.28 us | 16.482 us | 15.417 us | | SortArray | 20000 | Random | 101,550.87 us | 245.378 us | 272.737 us | | SortArray | 20000 | Sorted | 101,015.85 us | 667.370 us | 819.590 us |
Random and sorted numbers take almost the same time at every size. Both runs make exactly the same comparisons. The sorted run takes at most 12 percent less time, because it never moves a value and never updates smallestVal. On 2,000 random numbers, that index changes about 12,000 times, next to almost two million comparisons.
The growth from row to row is O(N²) at work: ten times more elements take 80 to 100 times longer, about 1.1 milliseconds for 2,000 random numbers, and about 0.1 seconds for 20,000.
Selection sort performs poorly when compared to other sorting algorithms such as merge sort, which runs in O(N log N).
Conclusion
So, in this article, we’ve learned about the selection sort algorithm and its time and space complexity. We’ve covered how to implement the selection sort in C#, and also when we should use it and when not.Â
Selection sort keeps swaps to a minimum, but it never makes fewer than n(n − 1) / 2 comparisons. Heap sort keeps the same idea of selecting the next value and finds it with a heap, which brings the time down to O(N log N). In real code we would call Array.Sort() instead, and our quicksort article looks at the algorithm behind it.
Tested with .NET 10.0.10, BenchmarkDotNet 0.15.8 and MSTest 4.5.2.






