Algorithms with C# · Lesson 8

Insertion sort

Maintain a sorted prefix as each value is inserted.

How it works

Insertion sort grows a sorted prefix from left to right. It saves the next value, shifts larger prefix elements one position right, and writes the saved value into the gap. The strict greater-than comparison preserves the relative order of equal values, making this implementation stable. The algorithm is easy to inspect and can work well for very small or nearly sorted inputs, but reverse-ordered data requires a number of shifts that grows quadratically with length.

Prefer the platform’s sorting APIs for ordinary application work unless there is a measured reason or an educational purpose for implementing the algorithm.

Trace the first two iterations by hand, then test an already sorted array and a reverse-ordered array. Count shifts to see why the input order changes the amount of work.

A working example

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

var values = new[] { 4, 1, 3, 2 };
for (var i = 1; i < values.Length; i++)
{
    var value = values[i]; var j = i - 1;
    while (j >= 0 && values[j] > value) { values[j + 1] = values[j]; j--; }
    values[j + 1] = value;
}
Console.WriteLine(string.Join(",", values));

Expected output

1,2,3,4
Try this
Save the value before shifting elements over its original position.