Data Structures and Algorithms • C# examples
Selection Sort and Insertion Sort
Compare two in-place quadratic sorts and identify when insertion sort performs well.
Concept
Selection sort selects the smallest remaining element and places it at the next output position; it makes few swaps but always performs quadratic comparisons. Insertion sort grows a sorted prefix by shifting larger values. It is stable in its usual form and efficient for small or nearly sorted inputs.
How to approach it
For selection sort, choose the next minimum. For insertion sort, shift the sorted prefix until the key’s insertion point is reached.
Complexity
Both O(n²) worst case; insertion sort is O(n) on already sorted data; both use O(1) extra space.
C# example
for (int i = 0; i < values.Length - 1; i++)
{
int smallest = i;
for (int j = i + 1; j < values.Length; j++)
if (values[j] < values[smallest]) smallest = j;
(values[i], values[smallest]) = (values[smallest], values[i]);
}
for (int i = 1; i < values.Length; i++)
{
int key = values[i], j = i - 1;
while (j >= 0 && values[j] > key)
values[j + 1] = values[j--];
values[j + 1] = key;
}
Expected result or behavior
Insertion sort maintains an ascending prefix after each iteration.
Practice exercise
Explain why changing `>` to `>=` can change stability for equal keys.
Key takeaway: Algorithm choice depends on input size, order, and the cost of comparisons and moves.