Sub topic 11
Worked example: insertion sort
This chapter assumes you know loops, list indexing, and sums like 1 + 2 + ... + n. It also assumes you have seen the best, worst, and average case defined, and have worked through linear search. Here we apply the same method to a sorting algorithm.
The cost model
Insertion sort builds a sorted prefix one element at a time. For each position i, it takes the element key = a[i] and compares it with the elements to its left. It shifts larger elements one slot right, then drops key into the gap.
We count one operation: a comparison of a[j] with key. Input size is n, the number of elements. Shifts happen at most once per comparison, so they do not change the shape of the count.
def insertion_sort_comparisons(values):
a = list(values)
comparisons = 0
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0:
comparisons += 1
if a[j] > key:
a[j + 1] = a[j]
j -= 1
else:
break
a[j + 1] = key
return comparisons
n = 6
print(insertion_sort_comparisons(range(n))) # sorted input: n - 1 = 5
print(insertion_sort_comparisons(range(n, 0, -1))) # reversed input: n(n-1)/2 = 15Best case: sorted input
If the input is already sorted, a[i - 1] > key is false at the first check. The inner loop stops after one comparison for each i. The outer loop runs for i = 1 to n - 1, so the total is n - 1 comparisons.
Worst case: reverse sorted input
With distinct values in reverse order, every key is smaller than everything to its left. The inner loop runs until j falls below 0, so position i costs i comparisons. The total is:
1 + 2 + ... + (n - 1) = n(n - 1)/2
For n = 6 that is 15, which matches the output above.
Average case: random order
Assume all orderings of n distinct values are equally likely. For a given i, the key lands in any of i + 1 positions among the sorted prefix with equal probability. On average it moves about half the prefix, so position i costs roughly i/2 comparisons, plus a little extra for the final failed comparison. The total is close to n(n - 1)/4. The exact formula is more intricate, so we check it by brute force.
from itertools import permutations
def insertion_sort_comparisons(values):
a = list(values)
comparisons = 0
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0:
comparisons += 1
if a[j] > key:
a[j + 1] = a[j]
j -= 1
else:
break
a[j + 1] = key
return comparisons
n = 5
counts = [insertion_sort_comparisons(p) for p in permutations(range(n))]
print(min(counts), max(counts), sum(counts) / len(counts))This runs the sort on all 120 orderings of five values. The minimum is 4 (n - 1), the maximum is 10 (n(n - 1)/2), and the mean falls between them, at roughly half the worst case plus a small linear term.
Summary of counts
| Case | Input | Comparisons | Growth |
|---|---|---|---|
| Best | Already sorted | n - 1 | Linear |
| Average | Uniformly random order | About n(n - 1)/4 plus a linear term | Quadratic |
| Worst | Reverse sorted | n(n - 1)/2 | Quadratic |
Exercise
For n = 4, how many comparisons does insertion sort make on the input [2, 1, 4, 3]?
Show answer
Index 1: key 1 is compared with 2, which is larger, so it shifts. j reaches -1 and the loop ends, giving 1 comparison. Index 2: key 4 is compared with 2, which is not larger, giving 1 comparison. Index 3: key 3 is compared with 4, which is larger, so it shifts. Then 3 is compared with 2, which is not larger. That is 2 comparisons. The total is 1 + 1 + 2 = 4, which is between the best case (3) and the worst case (6).