Insertion sort
easy 14 minInsertion sort builds a sorted prefix one value at a time: it takes the next value, shifts every bigger value in the prefix one slot right, and drops the value into the gap.
Remember it
The few things worth knowing cold, and how to make them stick.
Memory hook
Pick up a card, slide it left past the bigger ones, drop it in the gap.
Sorting a hand of playing cards. Your left hand holds cards already in order. You pick up a new card with your right hand, scan your hand from right to left, and slide it in where the card on its left is smaller and the card on its right is bigger.
Cheat sheet
- Best
- O(n), sorted input, n - 1 comparisons
- Average
- O(n²), about n(n-1)/4 shifts
- Worst
- O(n²), n(n-1)/2 shifts on reversed input
- Space
- O(1), in place
- Shifts
- equal to the number of inversions
- Stable
- Yes, use > not >=
- Adaptive and online
- Yes
- Inner loop
- while j >= 0 and arr[j] > key
- Insert at
- j + 1
Spot it when you see
- Data is nearly sorted or only a few values are out of place.
- The input is tiny, a few dozen values or fewer.
- Values arrive one at a time and the list must stay sorted.
- A stable, in-place, simple sort is required.
- Each element is at most k places from its sorted position.
- Sorting a linked list where splicing is cheap.
Tricks that stick
- SCIP: Scan, Compare, Insert, Progress.
- Sorted in, n out. Reversed in, n squared out.
- Count the out-of-order pairs and you have counted the shifts.
- Shift, do not swap: hold the key in your hand while the bigger cards slide right.
- The gap is always one right of where j stops.
Do not forget
- Checking arr[j] before j >= 0: arr[-1] reads the last element in Python.
- Forgetting to save the key before the first shift overwrites it.
- Writing the key at j instead of j + 1.
- Using >= and losing stability.
- Thinking binary search makes it O(n log n): the shifts are still quadratic.
- Using it on large random data instead of the built-in sort.