ZetCode

C# Insertion Sort

last modified November 6, 2026

In this article we implement the insertion sort algorithm in C#. We trace the algorithm step by step, write a generic stable version, keep a list sorted as new values arrive, and measure how the speed depends on the order of the input.

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.

Insertion sort algorithm

Insertion sort works the way many people sort playing cards in their hand. The array is divided into a sorted part at the beginning and an unsorted part after it. The algorithm takes the first unsorted element, shifts the larger elements of the sorted part one position to the right, and inserts the element into the gap.

PropertyValue
Best caseO(n), for sorted input
Average and worst caseO(n²)
Extra memoryO(1), sorts in place
Stableyes

Insertion sort is fast for small arrays and for arrays that are almost sorted. For this reason, it is part of hybrid algorithms. The introsort algorithm behind Array.Sort switches to insertion sort for partitions of 16 or fewer elements.

C# insertion sort example

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

Program.cs
int[] nums = [12, 11, 13, 5, 6, 1, 20];

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

static void InsertionSort(int[] arr)
{
    for (int i = 1; i < arr.Length; i++)
    {
        int key = arr[i];
        int j = i - 1;

        while (j >= 0 && arr[j] > key)
        {
            arr[j + 1] = arr[j];
            j--;
        }

        arr[j + 1] = key;
    }
}

The method sorts the array in place. The sorted part initially contains only the first element, so the loop starts at index 1.

int key = arr[i];
int j = i - 1;

The key is the element to be inserted. The index j walks the sorted part from right to left.

while (j >= 0 && arr[j] > key)
{
    arr[j + 1] = arr[j];
    j--;
}

Every element greater than the key is shifted one position to the right. The loop stops at the first element that is less than or equal to the key, or at the beginning of the array.

arr[j + 1] = key;

The key is placed into the gap left by the shifting.

$ dotnet run
1 5 6 11 12 13 20

Insertion sort step by step

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

Program.cs
int[] nums = [7, 3, 9, 1, 5];

InsertionSort(nums);

static void InsertionSort(int[] arr)
{
    for (int i = 1; i < arr.Length; i++)
    {
        int key = arr[i];
        int j = i - 1;

        while (j >= 0 && arr[j] > key)
        {
            arr[j + 1] = arr[j];
            j--;
        }

        arr[j + 1] = key;

        Console.WriteLine($"insert {key}: [{string.Join(" ", arr[..(i + 1)])}] {string.Join(" ", arr[(i + 1)..])}");
    }
}

In each step, the sorted part grows by one element. When 1 is inserted, all three elements of the sorted part are shifted; when 9 is inserted, nothing moves.

$ dotnet run
insert 3: [3 7] 9 1 5
insert 9: [3 7 9] 1 5
insert 1: [1 3 7 9] 5
insert 5: [1 3 5 7 9] 

Generic insertion sort

The generic version works on a Span<T> and takes an IComparer<T>. A span can point to an array, to a part of an array, or to stack memory.

Program.cs
Job[] jobs =
[
    new("backup", 2), new("deploy", 1), new("report", 3),
    new("review", 1), new("cleanup", 3), new("test", 2),
];

InsertionSort(jobs.AsSpan(), Comparer<Job>.Create((a, b) => a.Priority.CompareTo(b.Priority)));

foreach (var job in jobs)
{
    Console.WriteLine($"{job.Priority} {job.Name}");
}

Span<string> words = ["pear", "apple", "plum", "fig"];
InsertionSort(words, StringComparer.Ordinal);
Console.WriteLine(string.Join(" ", words.ToArray()));

static void InsertionSort<T>(Span<T> items, IComparer<T> comparer)
{
    for (int i = 1; i < items.Length; i++)
    {
        T key = items[i];
        int j = i - 1;

        while (j >= 0 && comparer.Compare(items[j], key) > 0)
        {
            items[j + 1] = items[j];
            j--;
        }

        items[j + 1] = key;
    }
}

record Job(string Name, int Priority);

We sort jobs by priority, and then a span of strings.

while (j >= 0 && comparer.Compare(items[j], key) > 0)

An element is shifted only if it is strictly greater than the key. Elements with an equal key stay before it, so the sort is stable: deploy stays before review, and backup before test.

InsertionSort(jobs.AsSpan(), Comparer<Job>.Create((a, b) => a.Priority.CompareTo(b.Priority)));

The AsSpan method creates a span over the whole array. The sort modifies the array through the span.

Span<string> words = ["pear", "apple", "plum", "fig"];
InsertionSort(words, StringComparer.Ordinal);

A collection expression can initialize a span directly. The StringComparer.Ordinal comparer compares strings by their character codes.

$ dotnet run
1 deploy
1 review
2 backup
2 test
3 report
3 cleanup
apple fig pear plum

Keeping a list sorted

Insertion sort is an online algorithm: it can sort data as it arrives. The List<T>.BinarySearch method finds the insertion point in O(log n) time, which makes it easy to keep a list sorted.

Program.cs
List<double> readings = [];

foreach (double value in new[] { 21.5, 19.8, 23.1, 20.4, 22.0, 18.9 })
{
    int idx = readings.BinarySearch(value);
    readings.Insert(idx < 0 ? ~idx : idx, value);

    double median = readings.Count % 2 == 1
        ? readings[readings.Count / 2]
        : (readings[readings.Count / 2 - 1] + readings[readings.Count / 2]) / 2;

    Console.WriteLine($"{value,5}: [{string.Join(", ", readings)}] median {median:F2}");
}

We insert temperature readings one by one and print the running median.

int idx = readings.BinarySearch(value);
readings.Insert(idx < 0 ? ~idx : idx, value);

If the value is not in the list, BinarySearch returns the bitwise complement of the index of the next larger element. The ~ operator turns it back into the insertion index. The Insert method shifts the following elements to the right, just as insertion sort does.

double median = readings.Count % 2 == 1
    ? readings[readings.Count / 2]
    : (readings[readings.Count / 2 - 1] + readings[readings.Count / 2]) / 2;

Because the list is always sorted, the median is the middle element, or the average of the two middle elements.

$ dotnet run
 21.5: [21.5] median 21.50
 19.8: [19.8, 21.5] median 20.65
 23.1: [19.8, 21.5, 23.1] median 21.50
 20.4: [19.8, 20.4, 21.5, 23.1] median 20.95
   22: [19.8, 20.4, 21.5, 22, 23.1] median 21.50
 18.9: [18.9, 19.8, 20.4, 21.5, 22, 23.1] median 20.95

Insertion sort on different inputs

The speed of insertion sort depends on how far the elements are from their final positions. The number of shifts equals the number of inversions, pairs of elements that are in the wrong order. The following example sorts 20,000 integers in three different orders.

Program.cs
#:property PublishAot=false

using System.Diagnostics;

const int N = 20_000;
var rnd = new Random(17);

int[] random = [.. Enumerable.Range(0, N).Select(_ => rnd.Next(1_000_000))];

int[] nearly = [.. Enumerable.Range(0, N)];
for (int i = 0; i < 50; i++)
{
    int x = rnd.Next(N), y = rnd.Next(N);
    (nearly[x], nearly[y]) = (nearly[y], nearly[x]);
}

int[] reversed = [.. Enumerable.Range(0, N).Reverse()];

Measure("random", random);
Measure("nearly sorted", nearly);
Measure("reversed", reversed);

int[] copy = [.. random];
var sw = Stopwatch.StartNew();
Array.Sort(copy);
Console.WriteLine($"{"Array.Sort, random",-20} {sw.Elapsed.TotalMilliseconds,9:F3} ms");

static void Measure(string label, int[] data)
{
    int[] copy = [.. data];
    var sw = Stopwatch.StartNew();
    long shifts = InsertionSort(copy);
    Console.WriteLine($"{label,-20} {sw.Elapsed.TotalMilliseconds,9:F3} ms {shifts,12:N0} shifts");
}

static long InsertionSort(int[] arr)
{
    long shifts = 0;

    for (int i = 1; i < arr.Length; i++)
    {
        int key = arr[i];
        int j = i - 1;

        while (j >= 0 && arr[j] > key)
        {
            arr[j + 1] = arr[j];
            j--;
            shifts++;
        }

        arr[j + 1] = key;
    }

    return shifts;
}

The nearly sorted array is created by 50 random swaps in a sorted array. The reversed array is the worst case.

#: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. A reversed array of n elements has n(n-1)/2 inversions; random data has about half as many. The nearly sorted array is sorted more than a hundred times faster than random data and is even faster than Array.Sort on random data.

$ dotnet run -c Release benchmark.cs
random                  64.825 ms  100,528,771 shifts
nearly sorted            0.494 ms      655,344 shifts
reversed               124.380 ms  199,990,000 shifts
Array.Sort, random       1.088 ms

Source

List<T>.BinarySearch method

In this article we have implemented the insertion 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.