TExcelTAD
Home › Sorting & Order Statistics › Decision Trees and the Comparison Lower Bound

Decision Trees and the Comparison Lower Bound

Merge sort and heapsort both make Θ(nlg⁡n)\Theta(n \lg n) comparisons in the worst case. Quicksort makes that many on average. Is there a cleverer comparison sort that needs only, say, nlg⁡nn \sqrt{\lg n}? No. This lesson proves that every algorithm that learns about its input only by comparing keys must make at least lg⁡(n!)=Ω(nlg⁡n)\lg(n!) = \Omega(n \lg n) 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 ai<aja_i < a_j (or ≤\le, ==, >>; 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 ai≤aja_i \le a_j.

Decision trees

Fix the input size nn. Any comparison sort, run on inputs of size nn, can be drawn as a decision tree: a binary tree in which

  • each internal node is a comparison ai≤aja_i \le a_j 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 n=3n = 3 by running it on every ordering of three keys and recording the questions asked. Keys are named a0,a1,a2a_0, a_1, a_2 by their input positions.

python · try it yourself
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):

text
                       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<=a0

Six 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 ⌈lg⁡(n!)⌉\lceil \lg(n!) \rceil comparisons on some input of size nn. Hence its worst case is Ω(nlg⁡n)\Omega(n \lg n).

Proof. Consider the decision tree for size nn. For a correct algorithm, each of the n!n! orderings of nn 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 n!n! reachable leaves. A binary tree of height hh has at most 2h2^h leaves. Therefore 2h≥n!2^h \ge n!, that is, h≥lg⁡(n!)h \ge \lg(n!), and since hh is an integer, h≥⌈lg⁡(n!)⌉h \ge \lceil \lg(n!) \rceil.

The order of growth of lg⁡(n!)\lg(n!) comes from Factorials, Stirling and the Iterated Logarithm. Stirling's formula n!=2πn (n/e)n(1+Θ(1/n))n! = \sqrt{2\pi n}\,(n/e)^n (1 + \Theta(1/n)) gives

lg⁡(n!)=nlg⁡n−nlg⁡e+12lg⁡n+O(1)≈nlg⁡n−1.443 n,\lg(n!) = n \lg n - n \lg e + \tfrac{1}{2} \lg n + O(1) \approx n \lg n - 1.443\, n,

so lg⁡(n!)=Θ(nlg⁡n)\lg(n!) = \Theta(n \lg n). The elementary bound n!≥(n/2)n/2n! \ge (n/2)^{n/2} already gives lg⁡(n!)≥n2lg⁡n2=Ω(nlg⁡n)\lg(n!) \ge \frac{n}{2} \lg \frac{n}{2} = \Omega(n \lg n), which is all the theorem needs.

Corollary. Heapsort and merge sort are asymptotically optimal comparison sorts: their O(nlg⁡n)O(n \lg n) upper bound matches the lower bound.

How close do real algorithms get?

The bound ⌈lg⁡(n!)⌉\lceil \lg(n!) \rceil 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 n⌈lg⁡n⌉−2⌈lg⁡n⌉+1n \lceil \lg n \rceil - 2^{\lceil \lg n \rceil} + 1, which the program confirms by trying every permutation for n≤7n \le 7) and of insertion sort, n(n−1)2\frac{n(n-1)}{2}.

python · try it yourself
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 nn, and within about half a comparison per key in general: its worst case lies between nlg⁡n−nn \lg n - n and about nlg⁡n−0.914 nn \lg n - 0.914\, n, against nlg⁡n−1.443 nn \lg n - 1.443\, n for the bound. An algorithm called merge insertion (Ford and Johnson, 1959) does even better and meets ⌈lg⁡(n!)⌉\lceil \lg(n!) \rceil exactly for every n≤11n \le 11; for n=12n = 12 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 n!n! orderings is the average depth of the n!n! leaves, and in a binary tree with NN leaves the average leaf depth is at least lg⁡N\lg N.

Proof sketch

Among binary trees with NN 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 lg⁡N\lg N. Alternatively, by Kraft's inequality ∑ℓ2−dℓ≤1\sum_\ell 2^{-d_\ell} \le 1, and by the convexity of 2−x2^{-x} (Jensen), 2−dˉ≤1N∑ℓ2−dℓ≤1N2^{-\bar d} \le \frac{1}{N} \sum_\ell 2^{-d_\ell} \le \frac{1}{N}, so the average depth satisfies dˉ≥lg⁡N\bar d \ge \lg N.

With N=n!N = n! this gives: every comparison sort makes at least lg⁡(n!)\lg(n!) comparisons on average over uniformly random orderings of distinct keys. Randomized quicksort's 1.39 nlg⁡n1.39\, n \lg n 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 nn keys n!n! orderings ⌈lg⁡(n!)⌉≈nlg⁡n−1.44n\lceil \lg(n!) \rceil \approx n \lg n - 1.44n
searching a sorted array of nn keys n+1n + 1 positions (found at ii, or not present) ⌈lg⁡(n+1)⌉\lceil \lg(n + 1) \rceil, met by binary search
merging two sorted lists of length nn (2nn)\binom{2n}{n} interleavings lg⁡(2nn)=2n−12lg⁡n+O(1)\lg \binom{2n}{n} = 2n - \tfrac{1}{2} \lg n + O(1)

For merging, the simple merge uses 2n−12n - 1 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 nn answers, giving lg⁡n\lg n, while the truth is n−1n - 1. 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 nn distinct keys have at least n!n! leaves?

  1. Because each comparison creates two leaves
  2. Because two different input orderings that reached the same leaf would be rearranged identically, so one of them would be output unsorted
  3. Because the tree must be complete
  4. Because there are n!n! comparisons

What is the minimum worst-case number of comparisons to sort 5 distinct keys, according to the decision-tree bound?

  1. 5
  2. 6
  3. 7
  4. 10

Which statement about the Ω(nlg⁡n)\Omega(n \lg n) lower bound is correct?

  1. It applies to every sorting algorithm
  2. It applies to comparison sorts, in the worst case and on average over random orderings
  3. It applies only to the worst case of deterministic algorithms
  4. It applies only to in-place sorts

Why does the counting argument give only lg⁡n\lg n for finding the minimum of nn keys?

  1. Because finding the minimum really takes lg⁡n\lg n comparisons
  2. Because there are only nn possible answers, and the argument only counts answers; the true bound n−1n - 1 needs an adversary argument
  3. Because the decision tree has height nn
  4. Because the minimum is unique