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).
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 aa[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
| Case | Input | Comparisons | Time |
|---|---|---|---|
| Best | sorted | ||
| Average | random | ||
| Worst | reverse sorted |
The work is proportional to the number of inversions: pairs with and . That is why insertion sort is excellent on nearly sorted input.
Implementations
- Standard: scan left from
keyand 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 withkey, otherwise equal elements swap places and the sort is no longer stable.
Related
References
- 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.