Insertion sort

Take each value and slide it left into its place among the already-sorted values: O(n²) in general, but very fast on small or nearly sorted arrays.

Description

Insertion sort works the way many people sort a hand of cards. The left part of the array is kept sorted. Each new value is taken from the right and slid left past larger values until it reaches its place.

On random data it's O(n²), like the other simple sorts. But its cost depends on how far values are from their final positions: on nearly sorted data each value moves only a step or two, so the sort is close to O(n). It's also stable, in place, and has very little overhead.

Those properties make insertion sort a workhorse inside faster algorithms. Timsort, Python's and Java's object sort, uses it on short runs; most quicksort and introsort implementations switch to insertion sort for small partitions of around 16 elements, where it beats O(n log n) algorithms in practice.

How it works

205172339415key

Inserting 3: shift 7 and 5 right, then drop 3 into the gap

  1. index 0: 2
  2. index 1: 5
  3. index 2: 7
  4. index 3: 3
  5. index 4: 9
  6. index 5: 1
Inserting 3: shift 7 and 5 right, then drop 3 into the gap

Step through: insertion sort (try the nearly sorted data)

291014371354122

Step 1 of 27Start with 8 values.

0 comparisons, 0 swaps
New data: , , ,

Complexity

OperationAverageWorst
Sort (average)O(n²)O(n²)
Nearly sorted inputk is the number of inversions: pairs out of order.O(n + k)O(n + k)
Already sortedO(n)O(n)

Space: O(1)

For arrays under a few dozen elements, insertion sort is usually the fastest sort there is, which is why faster algorithms hand small pieces to it.

TypeScript implementation

Insertion sort that shifts values rather than swapping, and a measurement of how much faster it is on nearly sorted data.

insertion-sort.ts
// Insertion sort: shift larger values right, then drop the key into the gap.

export function insertionSort(a: number[]): number {
  let shifts = 0;
  for (let i = 1; i < a.length; i++) {
    const key = a[i];
    let j = i - 1;
    while (j >= 0 && a[j] > key) {
      a[j + 1] = a[j]; // shift, don't swap
      j--;
      shifts++;
    }
    a[j + 1] = key;
  }
  return shifts;
}

export function demo(): string[] {
  const n = 2000;
  const random = Array.from({ length: n }, (_, i) => (i * 7919) % n);
  const nearly = Array.from({ length: n }, (_, i) => i);
  for (let k = 0; k < 10; k++) [nearly[k * 150], nearly[k * 150 + 1]] = [nearly[k * 150 + 1], nearly[k * 150]];
  return [
    `[29, 10, 14, 37, 13] → shifts: ${insertionSort([29, 10, 14, 37, 13])}`,
    `${n} random values: ${insertionSort(random).toLocaleString("en")} shifts`,
    `${n} nearly sorted values: ${insertionSort(nearly)} shifts (close to O(n))`,
  ];
}

When to use it

Use it when

  • Small arrays, roughly under 20–50 elements.
  • Data that is almost sorted, such as a sorted list with a few new items appended.
  • As the base case inside a divide-and-conquer sort.
  • Online sorting: values arrive one at a time and must stay sorted.

Avoid it when

  • Large, random data: use an O(n log n) sort.
  • Inserting many items into a large sorted collection: a balanced tree or heap is better.

Pitfalls

  • Swapping instead of shifting, which does three writes per step instead of one.
  • Using it on large random arrays, where it's quadratic.

Alternatives

Timsort

Choose it when you want insertion sort's speed on runs combined with O(n log n) overall.

Merge sort

Choose it when the data is large and you need stability.

Binary heap

Choose it when you only need the smallest items, not everything sorted.