/utils

Insertion Sort

Build a sorted prefix one element at a time by sliding each new key left into place. Simple, stable, in-place and fast on nearly sorted data.

SolvesSorting

best
O(n)
average
O(n^2)
worst
O(n^2)
space
O(1)

Insertion sort works the way many people sort a hand of cards: take the next card and slide it left until it sits after a smaller or equal one.

Already sorted: no key moves. That means no shifts and only n − 1 comparisons: O(n).

1021i324354657687

key = —

1def insertion_sort(a):2    for i in range(1, len(a)):3        key = a[i]4        j = i - 15        # shift larger values one slot right6        while j >= 0 and a[j] > key:7            a[j + 1] = a[j]8            j = j - 19        a[j + 1] = key10    return a
1 / 29

a[0..0] is sorted; next element is a[1].

comparisons
0
shifts
0

How it works

The array is split into a sorted prefix a[0..i) and the unsorted rest. Each round takes key = a[i], shifts every element of the prefix that is larger than key one slot to the right, and drops key into the gap. After round i, the prefix a[0..i] is sorted [1].

Complexity

CaseInputComparisonsTime
Bestsortedn−1n - 1O(n)O(n)
Averagerandom≈n2/4\approx n^2/4O(n2)O(n^2)
Worstreverse sortedn(n−1)2\frac{n(n-1)}{2}O(n2)O(n^2)

The work is proportional to the number of inversions: pairs (i,j)(i, j) with i<ji < j and ai>aja_i > a_j. That is why insertion sort is excellent on nearly sorted input.

Implementations

  • Standard: scan left from key and shift each larger value one slot right. Each comparison is followed by at most one shift. For fewer comparisons see binary insertion sort.

Pitfalls

  • Use a strict > when comparing with key, otherwise equal elements swap places and the sort is no longer stable.

Related

References

  1. T. H. Cormen et al., Introduction to Algorithms, 3rd ed., MIT Press, 2009.

Further reading

  • D. E. Knuth, The Art of Computer Programming, Volume 3: Sorting and Searching, 2nd ed., Addison-Wesley, 1998.

Full bibliography