Sub topic 6
Insertion Sort: Growing a Sorted Prefix One Element at a Time
This chapter assumes you can write loops over Python lists by index, read Big-O notation, and recall the cost model from earlier chapters, which counts comparisons, swaps, shifts, and extra space. Bubble sort and selection sort both work on the whole unsorted region during every pass. Insertion sort works differently. It keeps a sorted prefix at the front of the array. On each step it takes the next element and slides it left until it sits in the right place.
Many people sort a hand of playing cards this way. You hold the sorted cards in your left hand, pick up one new card, and push it into place among the cards you already hold.
The Core Idea
At the start of outer iteration i, the slice a[:i] is sorted. The element a[i] is called the key. The algorithm makes room for the key by moving every larger prefix element one position to the right. Then it writes the key into the gap.
Insertion sort's prefix is only sorted relative to itself. Selection sort's prefix already holds the i smallest values of the whole array, in their final positions. In insertion sort, an element that arrives later can still land in the middle or at the very front of the prefix. That difference explains most of how insertion sort behaves differently from the other two.
The Implementation
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]Here is what each line does:
- The outer loop starts at
1because a one-element prefixa[:1]is already sorted. key = a[i]saves the value before any shifting. The first shift writesa[i - 1]into positioni, which would overwrite the key if you had not saved it.- The inner
whileloop walks left through the prefix. It stops when it falls off the front (j < 0) or finds an element that is not greater than the key. a[j + 1] = a[j]copies one element one slot to the right. This is a shift: one write instead of the two writes a swap needs.- When the loop ends, position
j + 1is the gap, and the key goes there.
The sort is in place. Apart from the array itself it uses only key, i, and j, so its auxiliary space is O(1).
Tracing by Hand
Trace [12, 11, 13, 5, 6]. In the table, the bar | separates the sorted prefix from the unsorted rest. "Comparisons" counts evaluations of a[j] > key and "shifts" counts executions of a[j + 1] = a[j].
| i | key | Array before | Elements shifted right | Comparisons | Shifts | Array after | Column | Column |
|---|---|---|---|---|---|---|---|---|
| 1 | 11 | [12 \ | 11, 13, 5, 6] | 12 | 1 | 1 | [11, 12 \ | 13, 5, 6] |
| 2 | 13 | [11, 12 \ | 13, 5, 6] | none | 1 | 0 | [11, 12, 13 \ | 5, 6] |
| 3 | 5 | [11, 12, 13 \ | 5, 6] | 13, 12, 11 | 3 | 3 | [5, 11, 12, 13 \ | 6] |
| 4 | 6 | [5, 11, 12, 13 \ | 6] | 13, 12, 11 | 4 | 3 | [5, 6, 11, 12, 13] |
The totals are 9 comparisons and 7 shifts.
Look at how the inner loop ends in each row:
- At
i = 2, the key 13 is already larger than everything in the prefix. One comparison settles it, and nothing moves. - At
i = 3, the key 5 is smaller than everything in the prefix. The loop ends becausejdrops to-1, not because a comparison fails. The comparison count therefore equals the shift count. - At
i = 4, the loop ends on the failed comparison5 > 6. That gives one more comparison than shifts.
In general, each outer iteration makes either shifts or shifts + 1 comparisons. The difference depends on whether the key travels all the way to the front.
Shifting Versus Swapping
You can also write insertion sort with adjacent swaps, so that the key bubbles left one swap at a time. Both versions make the same comparisons and produce the same result. They differ in how many times they write to the list. The script below counts both quantities.
def insertion_sort_shift_counted(a):
comparisons = writes = 0
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0:
comparisons += 1
if a[j] <= key:
break
a[j + 1] = a[j]
writes += 1
j -= 1
a[j + 1] = key
writes += 1
return comparisons, writes
def insertion_sort_swap_counted(a):
comparisons = writes = 0
for i in range(1, len(a)):
j = i
while j > 0:
comparisons += 1
if a[j - 1] <= a[j]:
break
a[j - 1], a[j] = a[j], a[j - 1]
writes += 2
j -= 1
return comparisons, writes
data = [12, 11, 13, 5, 6]
x, y = list(data), list(data)
print("shift:", insertion_sort_shift_counted(x), x)
print("swap: ", insertion_sort_swap_counted(y), y)
# shift: (9, 11) [5, 6, 11, 12, 13]
# swap: (9, 14) [5, 6, 11, 12, 13]If an iteration moves the key past k elements, the shift version writes k + 1 slots: k shifts plus one placement. The swap version writes 2k slots. The gap is small on this input. On reverse-sorted data, where k is large in almost every iteration, the shift version does close to half the writes. Each swap also writes the key into a slot it will leave again on the next step, and the shift version skips that wasted work.
Common Errors
Forgetting to save the key
If you write a[j + 1] = a[j] and later read a[i], you read the value that was shifted into position i, not the original key. Save the key once, before the inner loop starts.
Reversing the loop condition
The condition must test the bound first: j >= 0 and a[j] > key. If you write a[j] > key and j >= 0, then a[-1] gets evaluated once j reaches -1. In Java this throws ArrayIndexOutOfBoundsException. In C it reads memory outside the array. In Python, a[-1] is a legal index for the last element, and and still returns false once j >= 0 fails. The sort therefore gives the right answer, and the bug stays hidden until someone ports the code to another language. Write the bound check first in every language.
Using `>=` instead of `>`
With a[j] >= key, the key also moves past elements equal to it. The output is still sorted, but equal keys end up in reverse order, and you do extra shifts for nothing. The strict > is what makes insertion sort stable. The stability chapter covers why that property matters.
Off-by-one in the placement
After the loop, j points at the last element that was not shifted, or at -1. The gap is at j + 1. Writing to a[j] overwrites a valid element and loses data.
Edge Cases
| Input | What happens | Comparisons | Shifts |
|---|---|---|---|
| `[]` or `[x]` | Outer loop body never runs | 0 | 0 |
| Already sorted, length n | Each key fails its first comparison | n − 1 | 0 |
| All elements equal | Same as sorted, because `>` is false for equal values | n − 1 | 0 |
| Reverse sorted, length n | Every key travels to the front | n(n − 1)/2 | n(n − 1)/2 |
| Only the last element out of place | Only the final iteration does work | about n − 1 + k | k |
The table shows the main pattern. The work tracks how far elements are from where they belong. A sorted input costs linear time. A reverse-sorted input costs quadratic time. Later chapters make this exact: the complexity chapter gives the full case analysis, and the inversions chapter shows that the shift count equals the number of out-of-order pairs.
Two Properties Worth Knowing Now
Insertion sort is online. It never looks at a[i + 1:] while it processes a[i], so it can sort elements as they arrive, one at a time, and keep a sorted list ready after every arrival. Selection sort cannot do this, because it has to scan all the remaining elements to find each minimum.
A sentinel can remove the bounds check. If you first move the smallest element to a[0], no key can move past it. The inner loop can then test only a[j] > key. Some implementations use this trick to save one comparison per inner step. The cost is one extra pass at the start to find the minimum, plus code that is harder to read.
Exercise
Trace insertion sort on [4, 3, 2, 10, 12, 1, 5, 6]. Give the array after each outer iteration, then total comparisons and total shifts.
Show answer
i=1 key 3: [3, 4, 2, 10, 12, 1, 5, 6] (1 comparison, 1 shift). i=2 key 2: [2, 3, 4, 10, 12, 1, 5, 6] (2, 2). i=3 key 10: unchanged (1, 0). i=4 key 12: unchanged (1, 0). i=5 key 1: [1, 2, 3, 4, 10, 12, 5, 6] (5, 5; the loop stops at j = -1). i=6 key 5: [1, 2, 3, 4, 5, 10, 12, 6] (3, 2). i=7 key 6: [1, 2, 3, 4, 5, 6, 10, 12] (3, 2). Totals: 16 comparisons, 12 shifts.
Exercise
After outer iteration i = 2 on the input [9, 7, 8, 1], the prefix is [7, 8, 9]. Is 9 in its final position? Explain how this differs from selection sort's prefix.
Show answer
No. The next key, 1, shifts 9 right to index 3, which only happens to be its final position here. In general, insertion sort's prefix is sorted only relative to itself, and any later key can move every prefix element right. Selection sort's prefix holds the i smallest values of the whole array, and those never move again.
Exercise
Write a function insert_sorted(a, x) that inserts x into an already sorted list a in place, keeps it sorted, and places x after any existing equal values. Use only the shifting technique from this chapter, without bisect or list.insert.
Show answer
def insertsorted(a, x): a.append(x) j = len(a) - 2 while j >= 0 and a[j] > x: a[j + 1] = a[j] j -= 1 a[j + 1] = x return a For example, insertsorted([1, 3, 3, 7], 3) returns [1, 3, 3, 3, 7], and the new 3 is last among the equal values. This is exactly one outer iteration of insertion sort, which is why the algorithm is online.