20. Insertion Sort
Grow a sorted prefix one item at a time, shifting bigger items right to make room. O(n^2) worst case but very fast on small or nearly sorted arrays.
How it works
Think of sorting playing cards in your hand. Take the next card (key), slide every bigger card in the sorted part one slot to the right, and drop the key into the gap. Real-world sorts such as Timsort (Python’s sorted) use insertion sort for short runs because it has tiny overhead.
Diagram
flowchart LR
s0["5 2 9 1 6 3"]
s1["2 5 9 1 6 3"]
s2["2 5 9 1 6 3"]
s3["1 2 5 9 6 3"]
s4["1 2 5 6 9 3"]
s5["1 2 3 5 6 9"]
s0 -->|"insert 2"| s1
s1 -->|"insert 9"| s2
s2 -->|"insert 1"| s3
s3 -->|"insert 6"| s4
s4 -->|"insert 3"| s5
Step-by-step trace
Input: Sort [5, 2, 9, 1, 6, 3].
| i | key | Shifted right | Inserted at | Array after |
|---|---|---|---|---|
| start | - | - | - | [5, 2, 9, 1, 6, 3] |
| 1 | 2 | [5] | 0 | [2, 5, 9, 1, 6, 3] |
| 2 | 9 | none | 2 | [2, 5, 9, 1, 6, 3] |
| 3 | 1 | [9, 5, 2] | 0 | [1, 2, 5, 9, 6, 3] |
| 4 | 6 | [9] | 3 | [1, 2, 5, 6, 9, 3] |
| 5 | 3 | [9, 6, 5] | 2 | [1, 2, 3, 5, 6, 9] |
Result: Sorted: [1, 2, 3, 5, 6, 9].
Complexity
| Operation | Time | Space |
|---|---|---|
| Worst / average | O(n^2) | O(1) |
| Best (already sorted) | O(n) | O(1) |
| Stable? | yes | - |
Python reference implementation
def insertion_sort(a):
a = list(a)
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j] # shift bigger items right
j -= 1
a[j + 1] = key
return a
Common mistakes and tips
- Use
>(not>=) when shifting so equal items keep their order (stability). - Running time is O(n + number of inversions), so nearly sorted data is fast.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Bubble Sort | Next: Merge Sort |