Comparing the simple sorts: best and worst cases, counted
🌍 In real life. Three classes must be lined up by height before the assembly.
- Class 6 just walked in from the field and is nearly in order: only two students are swapped.
- Class 7 played a prank and stands in exactly the reverse order, tallest first.
- Class 8 is a random muddle.
Which method is fastest? It depends on the line as much as on the method. A teacher who uses insertion sort finishes Class 6 almost at once; a teacher who uses selection sort takes just as long for Class 6 as for Class 8. This lesson counts the work exactly, so you can choose.
The idea in one sentence: compare sorts by counting their comparisons and swaps on the inputs that are best and worst for each, because a sort's cost depends on how out of order its input is.
Its words:
- best case, worst case: the input that makes a sort do the least, or the most, work
- average case: the work on a typical random input
- inversions: the number of pairs in the wrong order; it measures how unsorted a list is, from 0 (sorted) to n(n − 1)/2 (reversed)
- adaptive: a sort that does less work when the input is nearly sorted
How to compare, step by step:
- count comparisons (
a[j] > a[j + 1]and the like) and swaps, not seconds: counts are the same on every computer - try a sorted input, a reversed input and a random one
- work out the counts as formulas in n, and read off the Big-O
The worst case for bubble sort is a reversed line: every pair is an inversion, so every comparison swaps:
Insertion sort on a nearly sorted line is close to its best case: each value stops after one comparison, except the one out of place:
Why the counts come out this way. Bubble and insertion sort only ever swap neighbours that are in the wrong order, and each such swap removes exactly one inversion. So both make exactly as many swaps as the list has inversions: none for a sorted list, n(n − 1)/2 for a reversed one, and on average n(n − 1)/4 for a random one (each pair is equally likely to be either way round). Insertion sort's comparisons are its swaps plus at most one stopping comparison per value. Selection sort ignores the order completely: every pass scans the whole rest.
What they cost, by counting (n values; for 1,000 values in brackets):
- bubble sort: sorted: n − 1 comparisons, 0 swaps (999, 0). Reversed: n(n − 1)/2 of each (499,500).
- selection sort: always n(n − 1)/2 comparisons (499,500) and at most n − 1 swaps (999). Not adaptive.
- insertion sort: sorted: n − 1 comparisons, 0 swaps (999, 0). Reversed: n(n − 1)/2 of each (499,500). Random: about n²/4 of each (about 250,000).
All three are O(n²) in the worst case: for a million values that is about 500 billion comparisons, too slow. The sorts of Chapter 45 need about n log₂ n, about 20 million. Among the simple sorts, insertion sort is usually the best choice: stable, adaptive, and quick on small or nearly sorted lists.
def count_inversions(a):
count = 0
for i in range(len(a)):
for j in range(i + 1, len(a)):
if a[i] > a[j]:
count += 1
return count
def insertion_counts(a):
a = a[:] # count on a copy
comparisons = swaps = 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]
swaps += 1
j -= 1
return comparisons, swaps
for line in ([1, 2, 3, 4, 5, 6], [6, 5, 4, 3, 2, 1], [3, 6, 1, 5, 2, 4]):
print(line, count_inversions(line), insertion_counts(line))Mistakes and edge cases.
- timing instead of counting: the same sort can take different times on different computers, or twice on the same one; counts don't change
- "selection sort is fast on sorted input": it isn't; it still scans the whole rest every pass
- counting a comparison that never happened: when
jreaches 0 the loop stops without comparing anything - one example is not a worst case: a sort can be quick on the list you tried and slow on another; check the reversed and sorted inputs too
- small lists hide the difference: for 5 values every sort is instant; the gap only shows as n grows
Quiz
What does this print?
def count_inversions(a): count = 0 for i in range(len(a)): for j in range(i + 1, len(a)): if a[i] > a[j]: count += 1 return count print(count_inversions([3, 1, 2]), count_inversions([1, 2, 3]), count_inversions([3, 2, 1]))What does this print?
def insertion_counts(a): a = a[:] # count on a copy comparisons = swaps = 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] swaps += 1 j -= 1 return comparisons, swaps print(insertion_counts([1, 2, 4, 3, 5]), insertion_counts([5, 4, 3, 2, 1]))Which sort makes the same number of comparisons whatever order its input is in?
- Selection sort
- Insertion sort
- Bubble sort with the early stop
How many swaps does insertion sort make on a list of n values in reverse order?
- n(n − 1)/2: one per inversion, and every pair is inverted
- n − 1
- 0
You must sort small lists that are usually nearly sorted, and equal values must keep their order. Which simple sort fits best?
- Insertion sort: adaptive and stable
- Selection sort
- Any of them, they cost the same
insertion_sort([3, 1, 2]) should give [1, 2, 3], but gives [3, 2, 1]. Which line is wrong?
def insertion_sort(a): for i in range(1, len(a)): j = i while j > 0 and a[j - 1] < a[j]: a[j - 1], a[j] = a[j], a[j - 1] j -= 1 return a
Coding tasks
Write
count_inversions(a): how many pairs of positionsi < jhavea[i] > a[j]. It measures how far a line is from sorted.Write
insertion_counts(a): run insertion sort (the swap version: whilej > 0, comparea[j - 1]witha[j]and swap if the left one is bigger) on a copy ofa, and return the pair(comparisons, swaps). Count one comparison every timea[j - 1]anda[j]are compared.