Insertion Sort in C#: A Generic, Span-Based Implementation

Insertion sort builds the sorted result one element at a time. It takes the next element, walks left past every larger element, shifting each one a slot to the right, and drops the element into the gap. It is how most people sort a hand of cards.

On paper it is an O(n²) algorithm and loses to quick sort and merge sort on large inputs. In practice it is the fastest option for small arrays and for data that is already almost in order, which is why the sort built into .NET still uses it internally.

Usage

int[] numbers = { 1, 5, 4, 11, 20, 8, 2, 98, 90, 16 };

InsertionSort.Sort(numbers);

Console.WriteLine(string.Join(", ", numbers));
// 1, 2, 4, 5, 8, 11, 16, 20, 90, 98

Because the method is generic, it sorts string[], DateTime[] or any type that implements IComparable<T>.

Implementation

public static class InsertionSort
{
    public static void Sort<T>(T[] items) where T : IComparable<T>
        => Sort(items.AsSpan());

    public static void Sort<T>(Span<T> items) where T : IComparable<T>
    {
        for (int i = 1; i < items.Length; i++)
        {
            T current = items[i];
            int j = i - 1;

            // Shift every larger element one slot to the right.
            while (j >= 0 && items[j].CompareTo(current) > 0)
            {
                items[j + 1] = items[j];
                j--;
            }

            items[j + 1] = current;
        }
    }
}

How it works

Everything to the left of i is always sorted. Each pass of the outer loop takes items[i], holds it in current, and moves larger elements right until it finds the spot where current belongs.

Two details are easy to get wrong:

  • The inner loop shifts elements instead of swapping them. A swap writes two values per step; a shift writes one, and current is written once at the end. Implementations that swap on every step do roughly twice the work.
  • The comparison is > 0, not >= 0. Stopping at an equal element means equal values never pass each other, so the sort is stable. With >= it would still sort correctly, but equal elements would come out in reverse order.

On an array that is already sorted, the inner loop never runs: each element is compared once with its left neighbor and stays put. That is where the O(n) best case comes from. More generally, the work is proportional to the number of inversions (pairs that are in the wrong order), so “almost sorted” input is cheap.

Complexity

CaseTimeExtra space
Best (already sorted)O(n)O(1)
AverageO(n²)O(1)
Worst (reverse order)O(n²)O(1)

Insertion sort is stable and sorts in place.

When to use insertion sort

On a few dozen elements, insertion sort beats the O(n log n) algorithms because its inner loop is tiny and walks memory in order. That is why hybrid sorts switch to it for small pieces: the introsort behind Array.Sort and Span<T>.Sort hands partitions of 16 elements or fewer to insertion sort instead of partitioning them further.

It is also a good fit when you keep a list sorted while items arrive one by one, or when you re-sort data that only changed slightly, such as a leaderboard after a few scores moved.

For general-purpose sorting of large arrays, use Array.Sort. If you need a stable sort of a large collection, use merge sort or LINQ’s OrderBy. And if you need to find where a new item goes in an already sorted array, binary search finds the position in O(log n) comparisons, although the shift to make room is still O(n).

Related sorting examples

2 thoughts on “Insertion Sort in C#: A Generic, Span-Based Implementation”

Leave a Comment