Quant Memo
Core

The Comparison Lower Bound on Sorting

No sorting algorithm that only compares pairs of elements can beat roughly n log n comparisons in the worst case, and the proof is a clean counting argument about how many possible orderings exist.

Merge sort and heap sort both run in O(nlogn)O(n \log n) time, and a natural interview follow-up is: can a cleverer algorithm do better? For any algorithm that sorts purely by comparing pairs of elements (asking "is a<ba < b?" and nothing else), the answer is no — nlognn \log n comparisons, up to a constant factor, is provably the best possible in the worst case, for any input size nn.

The proof is a counting argument, not an algorithmic one. Any comparison-based sorting algorithm can be modelled as a decision tree: each internal node is one comparison, each branch is one possible outcome, and each leaf corresponds to one final, fully determined ordering of the input. For nn distinct elements there are n!n! possible orderings, and the algorithm must be able to reach a distinct leaf for every one of them — a tree with fewer than n!n! leaves would have two different true orderings mapping to the same leaf, meaning the algorithm couldn't tell them apart. A binary tree with n!n! leaves must have depth at least log2(n!)\log_2(n!), and by Stirling's approximation log2(n!)nlog2nn/ln2\log_2(n!) \approx n \log_2 n - n/\ln 2, which is Θ(nlogn)\Theta(n \log n). Since the tree's depth is exactly the worst-case number of comparisons the algorithm might need, no comparison-based algorithm can have worst-case comparisons below Θ(nlogn)\Theta(n \log n).

For n=4n = 4 elements there are 4!=244! = 24 possible orderings, requiring log224=5\lceil \log_2 24 \rceil = 5 comparisons in the worst case at minimum — matching what insertion sort or merge sort actually need on 4 elements, confirming the bound is tight, not just a loose estimate.

Any comparison-based sort must distinguish all n!n! possible orderings, forcing a decision tree of depth at least log2(n!)=Θ(nlogn)\log_2(n!) = \Theta(n \log n) — which is why no comparison sort can ever beat nlognn \log n in the worst case, and why non-comparison sorts (radix, counting sort) are the only way around this bound.

Related concepts

Practice in interviews

Further reading

  • Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms (comparison sort lower bound chapter)
ShareTwitterLinkedIn