Edexcel International Advanced Level Computer Science, point 10.3.4
This is the coding side of the insertion sort in 5.2.4. In-place means it sorts within the original list and needs no second list. In Unit 2 you may need to amend and write it.
The algorithm
- The first item is a sorted list of one.
- Take the next item (the key).
- Move left through the sorted part, shifting each larger item one place to the right.
- Put the key in the gap.
- Repeat for every remaining item.
Code
def insertion_sort(items):
for i in range(1, len(items)):
key = items[i] # the item to insert
# the last item of the sorted part
j = i - 1
while j >= 0 and items[j] > key:
items[j + 1] = items[j] # shift the larger item right
j = j - 1
items[j + 1] = key # insert the key into the gap
return items
print(insertion_sort([7, 3, 5, 1])) # [1, 3, 5, 7]
Points to notice:
- The outer loop starts at index 1, because index 0 is already "sorted".
- The inner loop is a
whilebecause the number of shifts isn't known. j >= 0is checked first, so thatitems[j]never has a negative index. (Order matters:andshort-circuits, 7.1.3.)- The comparison is
items[j] > key, not>=, so equal items stay in their original order (the sort is stable). - It uses no extra list, only the single variable
key: that's what in-place means. items[j + 1] = keyputs the key in the first gap (after the loop ends,j + 1is the gap).
Trace on [7, 3, 5, 1]
i |
key |
Shifts made | List after the pass |
|---|---|---|---|
| 1 | 3 | 7 moves right | [3, 7, 5, 1] |
| 2 | 5 | 7 moves right | [3, 5, 7, 1] |
| 3 | 1 | 7, 5, 3 move right | [1, 3, 5, 7] |
Detail of the pass with i = 3, key = 1:
j |
items[j] |
items[j] > 1? |
Action | List |
|---|---|---|---|---|
| 2 | 7 | Yes | items[3] = 7 |
[3, 5, 7, 7] |
| 1 | 5 | Yes | items[2] = 5 |
[3, 5, 5, 7] |
| 0 | 3 | Yes | items[1] = 3 |
[3, 3, 5, 7] |
| -1 | loop ends | items[0] = 1 |
[1, 3, 5, 7] |
Counting shifts and comparisons
def insertion_sort_counted(items):
shifts = comparisons = 0
for i in range(1, len(items)):
key = items[i]
j = i - 1
while j >= 0:
comparisons += 1
if items[j] > key:
items[j + 1] = items[j]
shifts += 1
j -= 1
else:
break
items[j + 1] = key
return items, shifts, comparisons
print(insertion_sort_counted([9, 4, 6, 2])) # ([2, 4, 6, 9], 5, 6)
# ([1, 2, 3, 4, 5], 0, 4)
print(insertion_sort_counted([1, 2, 3, 4, 5]))
# ([1, 2, 3, 4, 5], 10, 10)
print(insertion_sort_counted([5, 4, 3, 2, 1]))
| List | Shifts | Behaviour |
|---|---|---|
Sorted [1, 2, 3, 4, 5] |
0 | Best case: each key is compared once, so about comparisons |
Reversed [5, 4, 3, 2, 1] |
10 | Worst case: each key moves all the way, so about |
Variations
- The order: the comparison in the
whilecondition decides the order, so reversing the comparison reverses the sort. - Sorting records: compare the right field: for products sorted by price,
items[j]["price"] > key["price"]. - Sorting items as they arrive: insert each new item into an already sorted list.
Testing
tests = [[], [1], [2, 1], [3, 3, 3], [7, 3, 5, 1],
[1, 2, 3], [3, 2, 1], [4, -2, 0]]
for t in tests:
assert insertion_sort(t[:]) == sorted(t)
print("All insertion sort tests passed")
Insertion sort and bubble sort in code
| Insertion sort | Bubble sort | |
|---|---|---|
| Inner loop | while (shifts until the place is found) |
for (compares every pair) |
| Moves items by | Shifting (one write per move) | Swapping (three assignments per swap) |
| Sorted part | Left (grows) | Right (grows) |
| Nearly sorted data | Very fast | Fast (with early exit) |
| Worst case | ||
| Extra memory | One variable (key) |
One variable (temp) |
Worked example
Task: sort the list of marks [60, 45, 82, 39] with an insertion sort, giving the list after each pass and the total number of shifts.
i |
key |
Shifts | List after |
|---|---|---|---|
| 1 | 45 | 1 (60) | [45, 60, 82, 39] |
| 2 | 82 | 0 | [45, 60, 82, 39] |
| 3 | 39 | 3 (82, 60, 45) | [39, 45, 60, 82] |
Total shifts: 1 + 0 + 3 = 4. The final list is [39, 45, 60, 82].
Why the pass at i = 2 is quick: 82 is already larger than everything in the sorted part, so the while condition fails at once and 82 is written back into its own place.
Exam tip: start the outer loop at 1, and check j >= 0 before items[j]. Be able to say why it is in-place (no second list) and why it is fast on nearly sorted data (few shifts). Show the list after each pass in a trace.
Check yourself
Why does the outer loop start at index 1?
The first item is already a sorted list of one, so insertion begins with the second item.
Why does the inner loop use while instead of for?
The number of shifts isn't known in advance: it depends on how far the key has to move, so the loop runs until the right place is found.
Why must j >= 0 be tested before items[j] > key?
To avoid using index −1 (which would wrongly look at the last item); and short-circuit evaluation stops the second test being made.
How many shifts does an insertion sort make on a sorted list?
None.