Counting Sort and Radix Sort
Counting sort and radix sort sort integers in linear time by counting occurrences instead of comparing elements pairwise, beating the usual n log n limit whenever the data has a small, known range.
Prerequisites: Sorting Algorithms Compared, Big-O Complexity
Comparison-based sorts like quicksort or mergesort can't beat in the worst case — that limit is provable, because any algorithm that only compares pairs of elements needs at least that many comparisons to distinguish all possible orderings. Counting sort sidesteps the limit entirely by never comparing elements at all: if you know every value in an array of integers falls between and , you can count how many times each value appears, then read off the sorted array directly from those counts, in time.
Radix sort extends the same idea to numbers too large to count directly (say, 32-bit integers, where would be billions). It sorts digit by digit — first by the ones digit, then the tens digit, then the hundreds, and so on — using counting sort as a stable subroutine at each digit position. After processing every digit, the whole array ends up fully sorted, in time where is the number of digits and is the number of possible digit values (10, for base-10 digits).
For example, sorting the array [170, 45, 75, 90] by ones digit first gives [170, 90, 45, 75], then by tens digit gives [170, 90, 45, 75] → [90, 170, 45, 75]... continuing through all digit positions leaves the fully sorted [45, 75, 90, 170] — no two elements were ever directly compared.
Counting sort and radix sort beat the comparison-sort barrier by exploiting a bounded range of values instead of pairwise comparisons, making them the right choice for sorting things like trade IDs, timestamps, or price ticks known to fall in a fixed, moderate range — but useless for arbitrary or unbounded data like floating-point returns.
Related concepts
Practice in interviews
Further reading
- Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms (Ch. 8)