Sub topic 1
Why Comparison Sorts Can't Beat n log n
Merge sort, heapsort, and quicksort (on average) all run in O(n log n) time. That shared cost comes from a limit on every algorithm that learns about its input only by comparing pairs of elements. This chapter proves that limit and shows where counting sort and radix sort get around it.
Prerequisites
This chapter assumes you can:
- Read basic Python (lists, loops, functions).
- Use Big-O notation for time and space.
- Explain how at least one comparison sort works, such as merge sort or quicksort.
- Work with logarithms, especially log base 2.
Later chapters also use binary representation and bitwise shift and mask operations.
The comparison model
A comparison sort is an algorithm whose only way to inspect the data is to ask questions like "is a[i] <= a[j]?" It can move elements around freely. It cannot look at a key's numeric value and use that value directly, for example as an array index.
Under that rule, the algorithm learns one bit of information from each comparison. To sort correctly, it has to work out which of the n! possible orderings of n distinct elements it was given.
Decision trees
You can draw any comparison sort, for a fixed input size n, as a decision tree. Each internal node is a comparison. Each branch is one of its two outcomes. Each leaf is a final ordering. A single run of the algorithm follows one path from the root to a leaf, so the worst-case number of comparisons equals the height of the tree.
The counting argument
The proof has three steps:
- A correct sort needs at least n! leaves, one for each possible input ordering. If two orderings ended at the same leaf, the algorithm would rearrange them the same way and get at least one of them wrong.
- A binary tree of height h has at most 2^h leaves.
- So 2^h ≥ n!, which gives h ≥ log2(n!).
To see how large log2(n!) is, look at the top half of its factors. n! contains at least n/2 factors that are each at least n/2, so n! ≥ (n/2)^(n/2). That gives log2(n!) ≥ (n/2) log2(n/2), which is Ω(n log n). Stirling's approximation gives the sharper result log2(n!) ≈ n log2 n − 1.44n.
No comparison sort can do better in the worst case. The same bound also holds for the average case, because the average depth of the leaves in a binary tree with n! leaves is at least log2(n!).
Checking the bound empirically
The following script counts merge sort's comparisons and prints them next to log2(n!):
import math
import random
def merge_sort(a, counter):
if len(a) <= 1:
return a
mid = len(a) // 2
left = merge_sort(a[:mid], counter)
right = merge_sort(a[mid:], counter)
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
counter[0] += 1
if left[i] <= right[j]:
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
out.extend(left[i:])
out.extend(right[j:])
return out
for n in [10, 100, 1000, 10000]:
data = random.sample(range(n * 10), n)
counter = [0]
assert merge_sort(data, counter) == sorted(data)
bound = math.lgamma(n + 1) / math.log(2) # log2(n!)
print(f"n={n:>6} comparisons={counter[0]:>8} log2(n!)={bound:>10.0f}")Merge sort's comparison count stays a little above log2(n!) at every size. In terms of comparisons, merge sort is close to optimal.
The loophole
The proof depends on one assumption: every step is a yes/no comparison. If you drop that assumption, the bound no longer applies.
Counting sort uses a key's value directly as an index (counts[x] += 1). A single such step chooses among k + 1 outcomes, so it does more than answer a two-way question. Radix sort applies the same idea to one digit at a time. Neither algorithm fits in a binary decision tree, so neither is bound by Ω(n log n).
The price is a restriction on the keys. They must be integers in a known range, or values that can be broken into such integers. The rest of this tutorial covers that trade.
Exercise
What is the minimum number of comparisons any comparison sort needs in the worst case to sort 4 distinct elements?
Show answer
There are 4! = 24 orderings, and log2(24) ≈ 4.58. The height must be a whole number, so at least 5 comparisons are needed in the worst case.
Exercise
Which step of the lower-bound proof fails for counting sort?
Show answer
Step 2 assumes every node in the decision tree has two children, which is true only when each step is a yes/no comparison. Counting sort indexes an array with the key, so one step can branch k + 1 ways. Its "tree" therefore fits n! leaves at a much smaller height.