Decision Trees and the Comparison Lower Bound
Merge sort and heapsort both make comparisons in the worst case. Quicksort makes that many on average. Is there a cleverer comparison sort that needs only, say, ? No. This lesson proves that every algorithm that learns about its input only by comparing keys must make at least comparisons in the worst case, and on average too. The proof does not look at any particular algorithm. It looks at what any algorithm could possibly learn from a sequence of yes/no answers.
The comparison model
A comparison sort gains information about the keys only through tests like (or , , ; all equivalent for this purpose). It may move keys around freely, but it may not look at their bits, use them as array indices or do arithmetic on them. Insertion sort, merge sort, heapsort and quicksort are all comparison sorts. Counting sort, which uses keys as indices, is not, and that is why it can beat the bound (Counting Sort and Stability).
For the lower bound we may assume the keys are distinct: an algorithm must in particular sort inputs without duplicates, so a lower bound for those is a lower bound for the algorithm. With distinct keys, the only test needed is .
Decision trees
Fix the input size . Any comparison sort, run on inputs of size , can be drawn as a decision tree: a binary tree in which
- each internal node is a comparison that the algorithm makes at that point, with a "yes" child and a "no" child for the two answers;
- each leaf is the point where the algorithm stops, labelled by the permutation it applies to produce the output.
A run of the algorithm is a path from the root to a leaf, and the number of comparisons in that run is the length of the path. So the worst-case number of comparisons is the height of the tree.
The program builds the decision tree of insertion sort for by running it on every ordering of three keys and recording the questions asked. Keys are named by their input positions.
from itertools import permutations
def insertion_sort_questions(keys):
"""run insertion sort on keys, return (list of (question, answer), output order of positions)"""
items = list(range(len(keys))) # sort positions, compare their keys
log = []
for i in range(1, len(items)):
j = i
while j > 0:
p, q = items[j - 1], items[j]
answer = keys[p] <= keys[q]
log.append((f"a{p} <= a{q}", answer))
if answer: break
items[j - 1], items[j] = q, p
j -= 1
return log, items
tree = {}
for perm in permutations([1, 2, 3]):
log, order = insertion_sort_questions(perm)
path = " -> ".join(f"{q}? {'yes' if a else 'no'}" for q, a in log)
leaf = " <= ".join(f"a{p}" for p in order)
print(f"input {perm}: {path} => {leaf}")
tree[tuple(log)] = order
print(f"leaves reached: {len(tree)} (3! = 6), height: {max(len(k) for k in tree)}")input (1, 2, 3): a0 <= a1? yes -> a1 <= a2? yes => a0 <= a1 <= a2
input (1, 3, 2): a0 <= a1? yes -> a1 <= a2? no -> a0 <= a2? yes => a0 <= a2 <= a1
input (2, 1, 3): a0 <= a1? no -> a0 <= a2? yes => a1 <= a0 <= a2
input (2, 3, 1): a0 <= a1? yes -> a1 <= a2? no -> a0 <= a2? no => a2 <= a0 <= a1
input (3, 1, 2): a0 <= a1? no -> a0 <= a2? no -> a1 <= a2? yes => a1 <= a2 <= a0
input (3, 2, 1): a0 <= a1? no -> a0 <= a2? no -> a1 <= a2? no => a2 <= a1 <= a0
leaves reached: 6 (3! = 6), height: 3
Drawn as a tree (yes to the left):
a0 <= a1 ?
yes / \ no
a1 <= a2 ? a0 <= a2 ?
yes / \ no yes / \ no
a0<=a1<=a2 a0 <= a2 ? a1<=a0<=a2 a1 <= a2 ?
yes / \ no yes / \ no
a0<=a2<=a1 a2<=a0<=a1 a1<=a2<=a0 a2<=a1<=a0Six leaves, height 3. No comparison sort can do better on three keys: two comparisons have only four possible answer sequences, which cannot distinguish six orderings.
The theorem
Theorem. Every comparison sort makes at least comparisons on some input of size . Hence its worst case is .
Proof. Consider the decision tree for size . For a correct algorithm, each of the orderings of distinct keys needs a different output permutation, so it must end at a different leaf: two orderings reaching the same leaf would be rearranged the same way, and at most one of them would come out sorted. So the tree has at least reachable leaves. A binary tree of height has at most leaves. Therefore , that is, , and since is an integer, .
The order of growth of comes from Factorials, Stirling and the Iterated Logarithm. Stirling's formula gives
so . The elementary bound already gives , which is all the theorem needs.
Corollary. Heapsort and merge sort are asymptotically optimal comparison sorts: their upper bound matches the lower bound.
How close do real algorithms get?
The bound is not always achievable, but it is surprisingly close. The program compares it with the exact worst case of merge sort (given by the known formula , which the program confirms by trying every permutation for ) and of insertion sort, .
import math
from itertools import permutations
def merge_sort_comparisons(a):
if len(a) <= 1:
return a, 0
mid = len(a) // 2
left, cl = merge_sort_comparisons(a[:mid])
right, cr = merge_sort_comparisons(a[mid:])
out, i, j, c = [], 0, 0, cl + cr
while i < len(left) and j < len(right):
c += 1
if left[i] <= right[j]: out.append(left[i]); i += 1
else: out.append(right[j]); j += 1
return out + left[i:] + right[j:], c
print(f"{'n':>3} {'ceil lg n!':>10} {'merge sort':>10} {'insertion':>9}")
for n in range(1, 13):
bound = math.ceil(math.log2(math.factorial(n))) if n > 1 else 0
k = math.ceil(math.log2(n)) if n > 1 else 0
formula = n * k - 2 ** k + 1
if n <= 7:
worst = max(merge_sort_comparisons(list(p))[1] for p in permutations(range(n)))
assert worst == formula # brute force agrees with the formula
print(f"{n:>3} {bound:>10} {formula:>10} {n * (n - 1) // 2:>9}") n ceil lg n! merge sort insertion
1 0 0 0
2 1 1 1
3 3 3 3
4 5 5 6
5 7 8 10
6 10 11 15
7 13 14 21
8 16 17 28
9 19 21 36
10 22 25 45
11 26 29 55
12 29 33 66
Merge sort stays within a few comparisons of the bound for small , and within about half a comparison per key in general: its worst case lies between and about , against for the bound. An algorithm called merge insertion (Ford and Johnson, 1959) does even better and meets exactly for every ; for the bound says 29, and it is known that 30 comparisons are needed, so the bound is not always tight.
The average case too
The theorem is about the worst case. Could an algorithm be fast on most inputs and slow only on a few? Not by much. The average number of comparisons over all orderings is the average depth of the leaves, and in a binary tree with leaves the average leaf depth is at least .
Proof sketch
Among binary trees with leaves, one with the smallest total leaf depth can be assumed to have every internal node with two children (a node with one child can be removed, shortening paths). Moving a pair of sibling leaves from the deepest level to below a shallower leaf never increases the total, so in an optimal tree all leaves are on two adjacent levels: the tree is "balanced", and its average leaf depth is at least . Alternatively, by Kraft's inequality , and by the convexity of (Jensen), , so the average depth satisfies .
With this gives: every comparison sort makes at least comparisons on average over uniformly random orderings of distinct keys. Randomized quicksort's is therefore within a factor of 1.39 of the best possible average, and randomization does not help get below the bound either: a randomized algorithm is a probability distribution over decision trees, and each of them obeys the bound.
Other lower bounds from the same argument
The counting argument works for any problem whose answers can be listed:
| Problem | Possible answers | Lower bound in the comparison model |
|---|---|---|
| sorting keys | orderings | |
| searching a sorted array of keys | positions (found at , or not present) | , met by binary search |
| merging two sorted lists of length | interleavings |
For merging, the simple merge uses comparisons, so it is optimal up to a lower-order term. The counting argument is weak for problems with few possible answers: finding the minimum has only answers, giving , while the truth is . Such problems need a different tool, the adversary argument, used in Minimum and Maximum Together.
Test yourself
Why must the decision tree of a correct comparison sort on distinct keys have at least leaves?
- Because each comparison creates two leaves
- Because two different input orderings that reached the same leaf would be rearranged identically, so one of them would be output unsorted
- Because the tree must be complete
- Because there are comparisons
What is the minimum worst-case number of comparisons to sort 5 distinct keys, according to the decision-tree bound?
- 5
- 6
- 7
- 10
Which statement about the lower bound is correct?
- It applies to every sorting algorithm
- It applies to comparison sorts, in the worst case and on average over random orderings
- It applies only to the worst case of deterministic algorithms
- It applies only to in-place sorts
Why does the counting argument give only for finding the minimum of keys?
- Because finding the minimum really takes comparisons
- Because there are only possible answers, and the argument only counts answers; the true bound needs an adversary argument
- Because the decision tree has height
- Because the minimum is unique