Insertion sort
Like sorting playing cards in your hand: take each item and put it in its place in the sorted part on the left.
Insertion sort works like sorting playing cards in your hand. The left part of the array is always sorted. In each
round, the next item (key) is taken out, the larger items in the sorted part move one place to the right, and
key goes into the gap.
- Time:
O(n²) - Space:
O(1) - CLRS, section 2.1
- Horowitz–Sahni, chapter 7
- Johnsonbaugh, chapter 4
Six mixed numbers that get sorted over a few rounds; good for following by hand.
def insertion_sort(a):for j in range(1, len(a)):key = a[j]i = j - 1while i >= 0:if a[i] <= key:breaka[i + 1] = a[i]i = i - 1a[i + 1] = keyreturn a
Start
Local variables
Orange = changed in this step
a list
Call stack
- insertion_sort()line 1
How the work grows with input size
Average of 12 random graphs per n (fixed seeds). Hollow marker = the input on screen.
- comparisons
- shift
- insert
- current input (n=6)
Show as a table
| n | comparisons | shift | insert |
|---|---|---|---|
| 4 | 5.1 | 3.3 | 3 |
| 6 | 10.9 | 7.6 | 5 |
| 8 | 17.6 | 12 | 7 |
| 10 | 28.4 | 21.3 | 9 |
| 12 | 38.7 | 29.4 | 11 |
| 14 | 54.3 | 43 | 13 |
| 16 | 70.8 | 58.4 | 15 |
Explanation
The idea
Insertion sort works like sorting playing cards in your hand. The left part of the array is always sorted. In each
round, the next item (key) is taken out, the larger items in the sorted part move one place to the right, and
key goes into the gap.
The steps
- Start at
j = 1;a[0..0]on its own is sorted. - Take out
key = a[j]. - Walk back with
ifromj − 1. Whilea[i] > key, movea[i]one place to the right. - When you reach an item
≤ key(or the start of the array), putkeyintoa[i + 1]. - Increase
jand repeat.
Cost
- Best case (already sorted): each
keyneeds a single comparison, soO(n). - Worst case (sorted backwards): key number
jhas to passjitems, son(n − 1)/2moves in total andO(n²). - The extra memory is only
O(1): the sort happens in place.
Stability
Because the loop stops at a[i] ≤ key, equal items never pass each other. Their relative order is kept, so the sort
is stable. Watch it on the "repeated items" input.
What to watch in the trace
- The
iandjarrows under the bars show the two indices, andkeyis written above the array. - An orange bar is the position written in this step. A bar with an orange outline is the one being compared with
key. - Compare the number of
shiftsteps in the best case and in the worst case.