Sub topic 13
The Ω(n log n) Lower Bound for Comparison Sorts
Prerequisites and the Comparison Model
Assume you know logarithms, permutations, and the basic behavior of sorting algorithms. This chapter uses the comparison model, where a sorting algorithm learns about keys only by asking questions such as “Is a[i] < a[j]?” Each comparison has two possible outcomes.
The input contains \(n\) distinct keys. The algorithm must determine their sorted order.
The Decision-Tree Argument
A comparison sort can be represented by a decision tree:
- Each internal node is one comparison.
- Each outgoing edge represents one comparison result.
- Each leaf represents the final order selected by the algorithm.
- The tree height is the maximum number of comparisons.
For \(n\) distinct keys, there are \(n!\) possible input orders. A correct sorting algorithm must reach a different leaf for every possible order. Therefore, its decision tree needs at least \(n!\) leaves.
A binary tree of height \(h\) has at most \(2^h\) leaves. Thus,
\[ 2^h \ge n! \]
Taking logarithms gives
\[ h \ge \log_2(n!) \]
Using the fact that \(\log(n!) = \Theta(n \log n)\), every comparison sort has a worst-case lower bound of
\[ \Omega(n \log n) \]
comparisons.
What the Bound Means
The lower bound applies to the worst case. It says that no comparison-based algorithm can guarantee fewer than a constant multiple of \(n \log n\) comparisons for all inputs.
| Algorithm | Worst-case time | Comparison-based |
|---|---|---|
| Merge sort | Θ(n log n) | Yes |
| Heap sort | Θ(n log n) | Yes |
| Quick sort | Θ(n²) | Yes |
| Counting sort | Θ(n + k) | No |
Merge sort and heap sort are asymptotically optimal comparison sorts because their worst-case time matches the lower bound. Quick sort matches the bound on average with suitable pivot choices, but its worst case remains quadratic.
Why Linear-Time Sorting Is Possible
The lower bound does not apply when an algorithm uses information other than comparisons. Counting sort examines key values and counts, while radix sort processes digits. Their running time depends on the key range or number of digits.
For example, counting sort can run in \(O(n+k)\) when every key is an integer in a manageable range of size \(k\). This does not contradict the lower bound because counting sort is not restricted to yes-or-no comparisons.
Exercise
For n = 4 distinct keys, what is the minimum possible worst-case number of comparisons for any comparison sort?
Show answer
At least ceil(log₂(4!)) = ceil(log₂(24)) = 5 comparisons.