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 is not a coincidence or a failure of imagination. Any algorithm that learns about its input only by comparing pairs of elements must, in the worst case, make about n log₂ n comparisons. This chapter proves that bound, measures it in Python, and identifies the one assumption that counting sort and radix sort drop to get around it.
Prerequisites
This chapter assumes you are comfortable with:
- Basic Python syntax, including lists, loops, and functions.
- Big-O notation for time and space complexity.
- At least one comparison sort, such as merge sort or quicksort.
- Logarithms, especially log₂, and the idea that a binary tree of height h has at most 2^h leaves.
Later chapters also use binary representation and bitwise shift and mask operations. This chapter does not need them.
What Counts as a Comparison Sort
A comparison sort is a sorting algorithm that gets information about the elements only by asking questions of the form "is a[i] < a[j]?" (or ≤, >, =). It may move, copy, and swap elements freely. What it may not do is look inside a key: it cannot use a key as an array index, extract its digits, or do arithmetic on it.
This rule covers every general-purpose sort in standard libraries. Python's sorted() (Timsort), C++'s std::sort (introsort), and Java's Arrays.sort for objects are all comparison sorts. They have to be, because they accept any type with an ordering, including strings, tuples, dates, and user-defined objects with a custom __lt__.
That generality has a cost, and the cost has a precise size.
The Decision Tree Model
Fix the input size n and assume the elements are distinct. Any deterministic comparison sort can be drawn as a decision tree:
- Each internal node is one comparison, such as "a < b?".
- Each node has two children: one for "yes" and one for "no".
- Each leaf is a finished answer: a permutation saying which input element goes in which output position.
- Running the algorithm on a specific input means following one path from the root to a leaf.
The number of comparisons on a given input equals the length of its path. The worst-case number of comparisons equals the height of the tree.
Here is a decision tree for sorting three distinct elements a, b, c:
The tree has six leaves, one per ordering of three elements, and its height is 3. No algorithm can sort three elements with only two comparisons in the worst case. Two yes/no answers can tell apart at most 2² = 4 outcomes, and there are 6.
The Counting Argument
The same reasoning works for any n.
- The tree needs at least n! leaves. The n distinct inputs can arrive in any of n! orders, and each order needs a different rearrangement to sort it. If two orders reached the same leaf, the algorithm would apply the same permutation to both and get at least one of them wrong.
- A binary tree of height h has at most 2^h leaves. Each level can at most double the number of nodes.
- So 2^h ≥ n!, which means h ≥ log₂(n!).
What remains is to show that log₂(n!) grows like n log n. A short bound is enough. The product n! = 1 · 2 · … · n contains at least n/2 factors that are each at least n/2, so:
n! ≥ (n/2)^(n/2)
Taking log₂ of both sides:
log₂(n!) ≥ (n/2) · log₂(n/2)
The right-hand side is Ω(n log n). Every comparison sort therefore makes Ω(n log n) comparisons in the worst case.
Stirling's approximation gives the sharper estimate:
log₂(n!) = n log₂ n − n log₂ e + O(log n) ≈ n log₂ n − 1.443 n
The leading constant is exactly 1. Merge sort's worst case is about n log₂ n − n comparisons, so it is within a linear term of optimal. Within the comparison model, the bound is tight as well as asymptotic.
How Big the Bound Is
The table compares the minimum worst-case comparison count, ⌈log₂(n!)⌉, with n log₂ n.
| n | n! | ⌈log₂(n!)⌉ | n log₂ n |
|---|---|---|---|
| 3 | 6 | 3 | 4.75 |
| 4 | 24 | 5 | 8 |
| 10 | 3,628,800 | 22 | 33.2 |
| 100 | about 9.33 × 10¹⁵⁷ | 525 | 664.4 |
| 1,000 | about 4.02 × 10²⁵⁶⁷ | 8,530 | 9,965.8 |
The gap between the two columns is the −1.443n term from Stirling's formula. For large n the ratio approaches 1.
Measuring It in Python
You can count the comparisons Python's built-in sort makes by wrapping a comparison function with functools.cmp_to_key. The script below compares that count with the information-theoretic bound. It uses math.lgamma(n + 1), which equals ln(n!), so it never builds the enormous integer n!.
import math
import random
from functools import cmp_to_key
def count_comparisons(a):
"""Return how many comparisons sorted() makes on list a."""
count = 0
def cmp(x, y):
nonlocal count
count += 1
return (x > y) - (x < y)
sorted(a, key=cmp_to_key(cmp))
return count
def comparison_lower_bound(n):
"""Minimum worst-case comparisons: ceil(log2(n!))."""
if n < 2:
return 0
return math.ceil(math.lgamma(n + 1) / math.log(2))
random.seed(1)
print(f"{'n':>6} {'sorted() random':>16} {'sorted() presorted':>19} "
f"{'log2(n!)':>9} {'n log2 n':>9}")
for n in [10, 100, 1000, 10000]:
shuffled = random.sample(range(10 * n), n)
presorted = sorted(shuffled)
print(f"{n:>6} {count_comparisons(shuffled):>16} "
f"{count_comparisons(presorted):>19} "
f"{comparison_lower_bound(n):>9} {round(n * math.log2(n)):>9}")On shuffled input, the count for sorted() lands a little above ⌈log₂(n!)⌉ and below n log₂ n. On presorted input it drops to n − 1. That second column does not break the theorem, as the next section explains.
Gotchas and Edge Cases
The bound is about the worst case and the average case
The theorem says the tree is tall. It does not say every path is long. Timsort detects an already sorted run with n − 1 comparisons, which is one short path in its tree. Some other inputs must then take longer paths. A related argument shows that the average path length over all n! orderings is also at least log₂(n!). A binary tree with n! leaves cannot have all of them shallow. This is why randomized quicksort cannot escape the bound either: its expected comparison count on any input is still Ω(n log n).
Duplicates reduce the number of outcomes
The proof assumes distinct elements. If the input contains only a few distinct values, there are fewer distinguishable outcomes. With n elements drawn from k values with multiplicities m₁, …, mk, the number of distinct sorted arrangements is the multinomial n! / (m₁! · … · mk!), and the lower bound shrinks to the log of that. For example, an array of n values that are all 0 or 1 needs only O(n) work in principle, and three-way partitioning quicksort gets close to this. Keep that observation in mind: a small range of key values is exactly the situation counting sort exploits.
The bound counts comparisons, not total time
The theorem limits comparisons. A comparison sort can also do extra copying, so its real running time can be much worse than n log n. On the other hand, nothing in the theorem limits algorithms that use operations other than comparisons.
The Escape Hatch: Stop Comparing
The decision tree argument depends on one assumption: each step answers a yes/no question, so it yields at most one bit of information. Change that assumption and the bound goes away.
Suppose the keys are integers in the range 0 to k. An algorithm can use a key directly as an array index: counts[x] += 1. That one operation branches k + 1 ways at once, because it sends the element straight to the bucket for its value with no comparison against any other element. A tree whose nodes have k + 1 children can have far more leaves at the same height.
| Property | Comparison sorts | Counting and radix sort |
|---|---|---|
| Information per step | One yes/no answer | A whole key value or digit, used as an index |
| Key requirement | Any total order | Integers in a bounded range, or keys that split into digits |
| Lower bound that applies | Ω(n log n) comparisons | None from the decision tree model |
| Typical running time | O(n log n) | O(n + k) or O(d(n + b)) |
The cost moves from comparisons to assumptions about keys. Counting sort needs a range k that is not much larger than n. Radix sort needs keys that break into a fixed number of digits. Floats, arbitrary objects, and custom orderings do not fit these assumptions without extra work. The rest of this tutorial builds these algorithms step by step, starting with what "integer keys in a known range" means.
Exercises
Exercise
What is the minimum worst-case number of comparisons needed to sort 5 distinct elements, according to the decision tree bound? Show the calculation.
Show answer
There are 5! = 120 possible orderings, so the tree needs at least 120 leaves. 2^6 = 64 < 120 ≤ 128 = 2^7, so the height is at least ⌈log₂ 120⌉ = 7 comparisons. (An algorithm that sorts 5 elements in 7 comparisons does exist, so the bound is exact for n = 5.)
Exercise
Python's sorted() sorts an already sorted list of 1,000 elements with 999 comparisons, which is far below log₂(1000!) ≈ 8,530. Why doesn't this contradict the lower bound?
Show answer
The bound limits the height of the decision tree, meaning the worst case, and also the average path length over all orderings. It does not limit individual paths. A sorted input follows one short path. Because the tree must still have at least 1000! leaves, many other inputs must follow paths of length at least about 8,530.
Exercise
An array holds n integers, each 0, 1, or 2, and each value appears exactly n/3 times. Using the counting argument, roughly how many comparisons does a comparison sort need in the worst case, and what does this suggest about inputs with few distinct keys?
Show answer
The number of distinct outcomes is n! / ((n/3)!)³. By Stirling's formula its log₂ is about n log₂ 3 ≈ 1.585n, so the bound is only linear in n. With few distinct key values there is much less information to discover, which is the opening that counting sort exploits by indexing on the key directly.