Sub topic 6
Insertion Sort: Growing a Sorted Prefix One Element at a Time
This chapter assumes you can write Python loops, index into lists, and read Big-O notation. It also uses the cost model from earlier in the tutorial. In that model, a shift is a single write that moves one element one position to the right.
Insertion sort works the way many people sort a hand of cards. The left part of the array is kept sorted. On each step you take the next element and slide it left until it sits in its correct place within that sorted part.
The Working Model
At the start of step i, the prefix a[:i] is sorted. The element a[i] is called the key, and it is the one being inserted. The algorithm:
- Copies
a[i]intokey, which frees its slot. - Walks left with index
j. Each element larger thankeymoves one slot to the right. - Stops at the first element that is not larger than
key, or at the left edge of the array. - Writes
keyinto the gap ata[j + 1].
Shifting is cheaper than swapping. A swap writes two values. Moving the key with swaps would write it again at every step. A shift writes once per larger element, and the key is written once at the end.
def insertion_sort(a):
for i in range(1, len(a)):
# a[:i] is sorted; insert a[i] into it.
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j] # shift right instead of swapping
j -= 1
a[j + 1] = key
return a
print(insertion_sort([12, 11, 13, 5, 6])) # [5, 6, 11, 12, 13]Tracing by Hand
Here is a trace on [12, 11, 13, 5, 6]. The bar | marks the end of the sorted prefix after each step.
| i | key | Comparisons | Shifts | Array after step | Column |
|---|---|---|---|---|---|
| 1 | 11 | 1 | 1 | 11 12 \ | 13 5 6 |
| 2 | 13 | 1 | 0 | 11 12 13 \ | 5 6 |
| 3 | 5 | 3 | 3 | 5 11 12 13 \ | 6 |
| 4 | 6 | 4 | 3 | 5 6 11 12 13 \ |
Look at steps 1 and 3. In both, the loop stops because j reaches -1, so no final comparison is made against an element. In step 2, one comparison is enough because 13 is already larger than everything in the prefix. That is how insertion sort gets cheap when the input is nearly sorted. A later chapter makes this precise with inversions.
The total is 9 comparisons and 7 shifts. Bubble sort or selection sort on the same array would make 10 comparisons.
Common Errors
- Forgetting to save the key. The first shift writes over
a[i]. If you reada[i]inside the loop instead ofkey, you compare against a value that has already been overwritten. - Off-by-one on placement. When the loop ends,
jpoints one slot to the left of the gap. Write toa[j + 1], nota[j]. - Using
>=instead of>. With>=the result is still sorted, but each equal element jumps ahead of its equal neighbors. That breaks stability, which the stability chapter covers. - Starting at
i = 0. A one-element prefix is already sorted, so start ati = 1. Starting at 0 does no harm, but the extra iteration does nothing.
Cost at a Glance
| Input | Comparisons | Shifts |
|---|---|---|
| Already sorted | n − 1 | 0 |
| Reverse sorted | n(n − 1)/2 | n(n − 1)/2 |
The algorithm sorts in place with O(1) extra space: one key variable and one index. The full best, average, and worst-case analysis comes in a later chapter.
Exercise
Trace insertion sort on [4, 3, 2, 1]. How many shifts happen at each step, and what is the total?
Show answer
Step i=1 makes 1 shift, giving 3 4 2 1. Step i=2 makes 2 shifts, giving 2 3 4 1. Step i=3 makes 3 shifts, giving 1 2 3 4. The total is 6 shifts, which equals n(n − 1)/2 for n = 4, the worst case.
Exercise
A colleague writes the loop condition as while a[j] > key and j >= 0. On which input from this chapter's trace can this produce a wrong result, and why?
Show answer
It can go wrong at step i=3 of [12, 11, 13, 5, 6]. After 11 shifts, j becomes -1 and Python evaluates a[-1] > key before it checks j >= 0. Here a[-1] is 6, and 6 > 5 is true, so the loop runs again. It writes a[0] into a[-1], overwriting the unprocessed 6 with a copy of 11, and then goes on to j = -2. The final list is wrong. Checking j >= 0 first stops the loop before any negative index is read.