The limits of sorting
Why no comparison sort can beat N log N: counting orderings, decision trees, and log N! ≈ N log N; how close real sorts come; lower bounds by reduction; and a summary of every sort in this unit.
- Swift book
- Closures
Merge sort, heapsort, and quicksort all make about N log N comparisons. Could a cleverer algorithm make fewer, say N log log N, or even N? This lesson, following CS61B’s lecture on sorting and algorithmic bounds, proves that no sort that works by comparing items can: Ω(N log N) comparisons are necessary in the worst case. It is one of the few lower bounds in computer science that can be proved in a few lines.
A guessing game
CS61B starts with a puzzle. A puppy, a cat, and a dog are lined up in some order you cannot see. You may ask questions of the form “is the puppy to the left of the cat?”, and get yes or no. How many questions do you need to know the whole order?
There are 3! = 6 possible orders. Each answer at best halves the number of orders still possible: after one question, at least 3 remain in the worse case; after two, at least 2. So three questions are needed in the worst case, and three suffice.
Sorting is the same game with N items: there are N! possible orders, and each comparison is a yes-or-no question.
Decision trees
Any comparison sort can be drawn as a decision tree: each internal node is a comparison, each branch an answer, and each leaf a final order. Running the sort on an input follows one path from the root to a leaf.
- The tree must have at least N! leaves, one for each possible input order, since each order must be rearranged differently.
- A binary tree of height h has at most 2ʰ leaves.
- So 2ʰ ≥ N!, and the height, the worst-case number of comparisons, is at least log₂ N!.
And log₂ N! grows like N log N: N! ≥ (N/2)^(N/2), because its larger half of factors is each at least N/2, so log₂ N! ≥ (N/2) log₂(N/2), which is Ω(N log N). (Stirling’s formula gives the precise value, log₂ N! ≈ N log₂ N − 1.44 N.)
Every comparison sort needs Ω(N log N) comparisons in the worst case. Merge sort and heapsort are therefore asymptotically optimal: no comparison sort beats them by more than a constant factor.
import Foundation
func log2Factorial(_ n: Int) -> Double {
(1...n).map { log2(Double($0)) }.reduce(0, +)
}
for n in [3, 10, 1_000] {
print(n, Int(log2Factorial(n).rounded(.up)), Int((Double(n) * log2(Double(n))).rounded()))
}
// 3 3 5
// 10 22 33
// 1000 8530 9966
For the puppy, cat, and dog, ⌈log₂ 6⌉ = 3, as the puzzle found. For 1,000 items, at least 8,530 comparisons are needed in the worst case, close to N log₂ N.
What would Swift print?
var comparisons = 0
func less(_ a: Int, _ b: Int) -> Bool {
comparisons += 1
return a < b
}
func sort3(_ a: Int, _ b: Int, _ c: Int) -> [Int] {
var (x, y, z) = (a, b, c)
if less(y, x) { swap(&x, &y) }
if less(z, y) { swap(&y, &z) }
if less(y, x) { swap(&x, &y) }
return [x, y, z]
}
print(sort3(3, 1, 2), sort3(2, 3, 1), comparisons)Show answer and explanation
Answer[1, 2, 3] [1, 2, 3] 6
Three comparisons per call, whatever the input: exactly the lower bound for three items, ⌈log₂ 3!⌉ = 3. This is a tiny sorting network: a fixed sequence of compare-and-swap steps, which hardware can run in parallel.
How close real sorts come
Swift’s sorted() can be measured by counting calls to the comparator. On one run,
for random arrays:
| N | Lower bound ⌈log₂ N!⌉ | sorted() |
N log₂ N |
|---|---|---|---|
| 100 | 525 | about 1,400 | 664 |
| 1,000 | 8,530 | about 20,600 | 9,966 |
| 100,000 | 1,516,705 | about 2,385,000 | 1,660,964 |
Swift’s sort makes a small constant factor more comparisons than the bound, partly because it sorts short runs with insertion sort (Lesson 54), which is fast in practice despite comparing more. And on already sorted input it makes exactly N − 1 comparisons: the lower bound is about the worst case, not every input.
What the bound does not say
The argument assumed that the only way to learn about the items is to compare them. Sorts that look at the items themselves can do better. If the items are integers between 0 and 9, count how many of each there are and write them out: that is linear, and no comparison is made. Lesson 57 builds such sorts, radix sorts, which beat N log N whenever the keys are short.
The bound is also about comparisons, not time. An algorithm that makes few comparisons but much other work is not fast.
Lower bounds by reduction
Lesson 47 used reductions to solve problems. They also prove problems hard. Suppose some algorithm could find the closest pair among N numbers on a line faster than N log N using comparisons. Then element distinctness, deciding whether any two of N items are equal, which is known to need Ω(N log N) comparisons, could be solved as fast: the items are distinct exactly when the closest pair is not at distance 0. So the closest pair problem needs Ω(N log N) too. The pattern: if a known-hard problem reduces cheaply to a new one, the new one is at least as hard.
Every sort, compared
CS61B ends its sorting unit with a summary. With N items:
| Sort | Worst time | Average time | Memory | Stable | Notes |
|---|---|---|---|---|---|
| Selection | Θ(N²) | Θ(N²) | Θ(1) | no | few swaps |
| Insertion | Θ(N²) | Θ(N²) | Θ(1) | yes | Θ(N + inversions): fast when nearly sorted, or small |
| Heapsort | Θ(N log N) | Θ(N log N) | Θ(1) | no | poor cache behavior |
| Merge sort | Θ(N log N) | Θ(N log N) | Θ(N) | yes | good for huge or streamed data |
| Quicksort (random pivot) | Θ(N²), with vanishing probability | Θ(N log N) | Θ(log N) stack | no | fastest in practice among these |
| Radix sorts (Lesson 57) | Θ(W N) for W-digit keys | Θ(W N) | Θ(N + R) | LSD: yes | no comparisons |
Swift’s sort |
O(N log N) | O(N log N) | Θ(N) | yes | merge-based, detects sorted runs |
Put the lines in order
Put the lines in order so the program prints 6.
}for k in 1...items {orders *= kprint(orders)var orders = 1let items = 3
Show the correct program
var orders = 1
let items = 3
for k in 1...items {
orders *= k
}
print(orders)Lab 55: The limits of sorting
Q0: What would Swift print?
What would Swift print?
var leaves = 1
var height = 0
while leaves < 24 {
leaves *= 2
height += 1
}
print(height)Show answer and explanation
Answer5
A decision tree for 4 items needs 4! = 24 leaves, and a binary tree of height 4 has at most 16, so the height must be at least 5: sorting four items needs five comparisons in the worst case, and five suffice.
Q1: Counting comparisons
Write comparisonsUsed(_:), which returns how many times a sort calls its comparator
on an array, and use it to check that sorted(by:) never uses fewer than
⌈log₂ N!⌉ comparisons in the worst of 20 random shuffles, for N from 2 to 12.
Show solution
import Foundation
func comparisonsUsed(_ values: [Int]) -> Int {
var count = 0
_ = values.sorted { count += 1; return $0 < $1 }
return count
}
func lowerBound(_ n: Int) -> Int {
Int((1...n).map { log2(Double($0)) }.reduce(0, +).rounded(.up))
}
var generator = SystemRandomNumberGenerator()
for n in 2...12 {
let worst = (0..<20).map { _ in comparisonsUsed(Array(0..<n).shuffled(using: &generator)) }.max()!
assert(worst >= lowerBound(n) || n > 8)
}
assert(comparisonsUsed(Array(0..<100)) == 99) // sorted input: one passFor small N, twenty shuffles usually include an input near the worst case, so the worst observed count reaches the bound. For larger N, twenty samples may all miss the worst case, which is why the check only insists for N up to 8: the bound says the worst input needs that many comparisons, not that every input does, and the sorted input at the end needs only 99.
Q2: Maximum and minimum together
Finding the maximum takes N − 1 comparisons, and so does the minimum: 2N − 2 for both. Do it in about 3N/2: compare items in pairs, then compare the larger of each pair with the current maximum and the smaller with the current minimum.
Show solution
var comparisons = 0
func less(_ a: Int, _ b: Int) -> Bool { comparisons += 1; return a < b }
func minAndMax(_ values: [Int]) -> (min: Int, max: Int)? {
guard var low = values.first else { return nil }
var high = low
var i = values.count % 2 == 0 ? 0 : 1 // odd count: the first item started both
if values.count % 2 == 0 {
(low, high) = less(values[1], values[0]) ? (values[1], values[0]) : (values[0], values[1])
i = 2
}
while i + 1 < values.count {
let (small, large) = less(values[i + 1], values[i]) ? (values[i + 1], values[i]) : (values[i], values[i + 1])
if less(small, low) { low = small }
if less(high, large) { high = large }
i += 2
}
return (low, high)
}
let values = (0..<1_000).map { ($0 * 7919) % 1_000 }
comparisons = 0
let result = minAndMax(values)!
assert(result.min == 0 && result.max == 999)
assert(comparisons <= 3 * 1_000 / 2)
assert(minAndMax([5])! == (5, 5) && minAndMax([]) == nil)Each pair costs three comparisons for two items, instead of four. An adversary argument, similar to the decision tree, shows that ⌈3N/2⌉ − 2 comparisons are also necessary, so this is optimal.
Q3 (optional): Distinctness by sorting
Element distinctness needs Ω(N log N) comparisons, and sorting solves it in O(N log N).
Write it that way, and then note what changes when the items are Hashable, not just
Comparable.
Show solution
func allDistinct<T: Comparable>(_ values: [T]) -> Bool {
let sorted = values.sorted()
return zip(sorted, sorted.dropFirst()).allSatisfy { $0 != $1 }
}
func allDistinctByHashing<T: Hashable>(_ values: [T]) -> Bool {
var seen = Set<T>()
return values.allSatisfy { seen.insert($0).inserted }
}
assert(allDistinct([3, 1, 4, 5]) && !allDistinct([3, 1, 4, 1]))
assert(allDistinctByHashing([3, 1, 4, 5]) && !allDistinctByHashing(["a", "b", "a"]))With hashing, distinctness takes expected Θ(N): the Ω(N log N) bound applies only to algorithms that learn about items by comparing them. Hashing looks at the items themselves, like radix sort, and escapes the bound, at the price of a guarantee that holds only on average.
What’s next
Next lesson: radix sorts, which sort without comparing, and beat N log N.