Skip to content
Part IA Lent Term

The Comparison-Based Sorting Lower Bound

Statement

Any comparison-based sorting algorithm must perform Ω(nlogn)\Omega(n \log n) comparisons in the worst case to sort nn elements.

A comparison-based sort uses only pairwise comparisons (\le or >>) to determine the relative order of elements. It makes no assumptions about the values (no counting, no hashing, no radix).

Proof via Decision Trees

A decision tree models the behaviour of any comparison-based sort:

  • Each internal node represents a comparison A[i]A[j]A[i] \le A[j], with two outgoing edges (Yes/No).
  • Each leaf represents a specific permutation of the input — the sorted output.
  • A path from root to leaf corresponds to the sequence of comparisons made on some input.

For nn distinct elements, there are n!n! possible input permutations. Since the algorithm must be correct for all permutations, the decision tree must have at least n!n! leaves.

A binary tree of height hh has at most 2h2^h leaves. Therefore:

2hn!2^h \ge n!

Taking logarithms:

hlog2(n!)h \ge \log_2(n!)

Using Stirling’s approximation (n!2πn(n/e)nn! \approx \sqrt{2\pi n}(n/e)^n):

log2(n!)=nlog2nnlog2e+O(logn)=Ω(nlogn)\log_2(n!) = n \log_2 n - n \log_2 e + O(\log n) = \Omega(n \log n)

The height hh is the number of comparisons on the longest path, so the worst-case number of comparisons is Ω(nlogn)\Omega(n \log n). \square

Implications

  • MergeSort at Θ(nlogn)\Theta(n \log n) is asymptotically optimal amongst comparison sorts.
  • HeapSort at O(nlogn)O(n \log n) is also optimal.
  • QuickSort averages Θ(nlogn)\Theta(n \log n) but can degrade to Θ(n2)\Theta(n^2).
  • No comparison sort can beat Ω(nlogn)\Omega(n \log n) in the worst case.

Lower Bound on Swaps

A separate result: the worst-case number of swaps is Ω(n)\Omega(n). Consider the input [2,3,,n,1][2, 3, \ldots, n, 1]. Every item is out of position, and each swap moves at most two items to their correct positions. Therefore at least n/2\lceil n/2 \rceil swaps are required. Selection Sort achieves this bound with Θ(n)\Theta(n) swaps.

Comparison Sorts vs Linear-Time Sorts

The Ω(nlogn)\Omega(n \log n) bound applies only to comparison-based sorts. Algorithms that exploit properties of the data can beat this bound:

SortBoundAssumption
Counting SortΘ(n+k)\Theta(n + k)Keys in range [0,k][0, k]
Radix SortΘ(d(n+k))\Theta(d(n + k))dd-digit numbers
Bucket SortΘ(n)\Theta(n) expectedUniform distribution over [0,1)[0, 1)

These are not comparison-based; they use counting, digit extraction, or hashing.

Summary

ConceptDetail
Lower boundΩ(nlogn)\Omega(n \log n) comparisons
Proof techniqueDecision tree model
Key inequality2hn!2^h \ge n!
Stirling’s approxlog(n!)nlognnloge\log(n!) \approx n \log n - n \log e
Optimal sortsMergeSort, HeapSort (comparison-based)
Swap lower boundΩ(n)\Omega(n)
ExceptionsLinear-time non-comparison sorts