function insertionSort(array: number[]) { for (let i = 1; i < array.length; i++) {const key = array[i];
let j = i - 1;
while (j >= 0 && array[j] > key) {array[j + 1] = array[j];
j--;
}
array[j + 1] = key;
}
}
Start: array[0] = 27 alone is a sorted prefix of length 1.
Understanding Insertion sort
The idea
Insertion sort keeps a sorted prefix and grows it one element at a time. It lifts the next value out, shifts every larger element of the prefix one slot to the right, and drops the value into the gap. It is how most people sort a hand of cards.
The cost is the number of shifts, which equals the number of inversions in the input. Sorted input needs n − 1 comparisons and no shifts; reversed input needs n²/2 of each. That adaptivity is why quick sort and Tim sort hand small or nearly sorted runs to it.
The four stages
Complexity
Versus its siblings
Pseudocode
INSERTIONSORT(array)
for i ← 1 to n − 1
key ← array[i]; j ← i − 1
while j ≥ 0 and array[j] > key
array[j + 1] ← array[j]; j ← j − 1
array[j + 1] ← key
When to use
Pitfalls
History
John Mauchly described insertion sort, with a binary search for the slot, in a 1946 lecture at the Moore School, one of the first published sorting methods for a computer. Its adaptivity made it the finishing step of every practical hybrid sort since, from Sedgewick's quick sort variants to Tim Peters' Tim sort in 2002.