Module 8 of 39

Counting sort, radix sort, and bucket sort

Understand the comparison-sorting limit and when key ranges let counting, radix, or bucket sorting go faster.

There is a reason many general sorting methods take Θ(n log n) time. If the only way to learn the order of two keys is to compare them, a sorting algorithm must distinguish among n! possible orders. A comparison has only two outcomes, so a decision tree needs enough levels to separate all those possibilities. In the worst case that requires Ω(n log n) comparisons.

Background for this page. A key is the field used for sorting. Stable sorting preserves the relative order of records with equal keys. You should be able to index a list. Related explanations: Insertion sort: a worked example and its cost · Big O, Big Omega, and Big Theta.

This is a limit on comparison sorting, not on every way to sort. If keys have more structure, we can use it. Suppose every score is an integer from 0 through 9. Instead of comparing every pair, count how often each score appears, then write the scores in order.

The key range replaces repeated key comparisons.

# Sort nonnegative integer keys from 0 through maximum.
def counting_sort(values, maximum):
    # Give every possible key its own count.
    counts = [0] * (maximum + 1)
    for value in values:
        # Reject a key outside the promised range.
        if value < 0 or value > maximum:
            raise ValueError('key outside range')
        counts[value] += 1
    # Write each key as many times as it appeared.
    result = []
    for value, frequency in enumerate(counts):
        result.extend([value] * frequency)
    return result

If there are n values and k possible keys, this version takes Θ(n + k) time and Θ(n + k) space including its output. It is attractive when k is not much larger than n. If the keys run from 0 to a billion but there are only ten values, allocating a billion counters is a poor choice. The input promise matters as much as the formula.

This simple version sorts bare numbers. For records that have both a key and other information, a stable counting sort uses cumulative counts to place whole records while preserving the original order of records with equal keys. Stability matters in radix sort, which sorts one digit or character position at a time. With d positions and a stable per-position method taking Θ(n + k), the total work is Θ(d(n + k)). If d or k grows too large, that cost may lose its advantage.

Bucket sort makes a different assumption: keys are spread roughly uniformly over a known interval. It places values into buckets, sorts each bucket, then joins them. Under the usual uniform-distribution assumption, its expected time can be Θ(n). A badly concentrated input can make one bucket large and spoil that expectation.

The lesson is not that one of these methods is “the fastest sort.” It is that an extra promise about the keys can let us do work a comparison-only method cannot. Before using that promise, check that real inputs actually satisfy it.

Why radix sort requires stable passes

For [21, 12, 11, 22], a stable units-digit pass gives [21, 11, 12, 22]. A stable tens-digit pass then gives [11, 12, 21, 22]. The second pass preserves the units order within each tens group. An unstable pass could reverse 11 and 12 and undo the earlier work. The counting-sort function assumes a nonnegative integer maximum and integer keys in range. It returns a new list. Its range check does not validate every possible Python object.

Practice. You have 30 exam scores, all integers from 0 to 100. Is counting sort plausible? What if the 30 keys are arbitrary integers that may be as large as a billion?

Answer. A count array of 101 entries is reasonable for the exam scores. A billion-entry array is unreasonable for only 30 arbitrary keys. A comparison sort or another structure would be a better starting point there.

Try another case. Show the two passes for [32, 11, 21, 12].

Reasoning. The units pass gives [11, 21, 32, 12]. The tens pass gives [11, 12, 21, 32].

View the full course and choose another topic.

Image preview

Fit