Sorting in Linear Time

Algorithms · Advanced Placement

Sorting in Linear Time: the big picture

Any sorting algorithm that determines order only by comparing pairs of elements can be modelled as a decision tree whose leaves are the possible permutations; since there are n factorial permutations and a binary tree of height h has at most two to the h leaves, the height and hence the worst-case number of comparisons is at least the logarithm of n factorial, which Stirling's approximation shows to be omega of n log n. Merge sort and heapsort therefore achieve the optimal comparison bound. Faster sorting is possible only by using information about the keys beyond their pairwise order. Counting sort assumes the keys are integers in a bounded range, counts the occurrences of each value and uses the cumulative counts to place elements directly, running in time linear in the number of elements plus the range and being stable, which matters for its use as a subroutine. Radix sort sorts by digit, least significant first, using a stable sort such as counting sort at each digit position, and runs in time proportional to the number of digits times the per-digit cost, which is linear when the word length is bounded. Bucket sort distributes elements into buckets by value under an assumption of uniform distribution and sorts each bucket, achieving linear expected time.

The Comparison Lower Bound & Decision Trees

There is a hard floor on comparison sorting, and the argument for it is elegant. Any comparison sort is a decision tree: each internal node is a comparison, each leaf is one of the n! possible permutations. A binary tree of height h has at most 2^h leaves, so h must be at least log(n!), which Stirling shows is Ω(n log n). That settles it — merge sort and heapsort are optimal, and no cleverness will produce a comparison sort that beats them. Going faster requires using information about the keys that comparisons do not reveal.

{{illustration:algos-l07-f1}}

{{illustration:algos-l07-f2}}

Key relations

- The decision tree bound. 2^h ≥ n! ⇒ h ≥ log₂(n!) = Θ(nlog n)

Counting Sort, Radix Sort & Bucket Sort

Escaping the comparison bound means using the keys themselves, not just their order. Counting sort tallies how many of each value there are and then places elements directly from the cumulative counts, running in time linear in the element count plus the key range — and crucially it is stable, which is what makes it usable as a subroutine. Radix sort builds on that, sorting digit by digit from least significant upward, which works only because each pass is stable. Bucket sort distributes by value and gives linear expected time if the keys are roughly uniform.

{{illustration:algos-l07-f3}}

{{illustration:algos-l07-f4}}

Key relations

- Linear-time sorting bounds. T_counting(n, k) = Θ(n + k) ; T_radix(n, b, r) = Θ(b/(log r)(n + r))