Sub topic 16
Counting, Radix, and Bucket Sort
This chapter assumes you know the Ω(n log n) lower bound for comparison sorts, the stability property of sorting algorithms, and basic loop analysis. Counting, radix, and bucket sort avoid the bound by not comparing keys with each other. They use the key values themselves, so they apply only when the keys have extra structure.
Why the lower bound does not apply
The lower bound comes from a decision tree. Each comparison has two outcomes, and a tree must have at least n! leaves to distinguish every input order. These three algorithms do something else. They use a key as an array index or split it into digits. A single array access can send an element to one of many places, so the decision tree model no longer describes them.
The price is an assumption about the input:
- Counting sort needs integer keys in a known range 0 to k-1.
- Radix sort needs keys made of a fixed number of digits.
- Bucket sort needs keys spread roughly evenly over a known interval.
Counting sort
Counting sort counts how many times each value occurs. It then turns the counts into final positions.
def counting_sort(a, k):
count = [0] * k
for x in a:
count[x] += 1
for v in range(1, k):
count[v] += count[v - 1]
out = [0] * len(a)
for x in reversed(a):
count[x] -= 1
out[count[x]] = x
return out
print(counting_sort([4, 1, 3, 4, 3, 0], 5))The output is [0, 1, 3, 3, 4, 4].
Worked trace
Take the input [4, 1, 3, 4, 3, 0] with k = 5.
- After the counting loop,
count = [1, 1, 0, 2, 2]. - The prefix-sum loop makes
count[v]equal to the number of elements less than or equal to v. The result is[1, 2, 2, 4, 6]. - The last loop scans the input from the right. The last element is 0. Decrementing
count[0]gives 0, so 0 goes toout[0]. - The next element from the right is 3.
count[3]drops from 4 to 3, so this 3 goes toout[3]. The earlier 3 will later go toout[2].
Because later equal keys are placed at later positions, equal keys keep their input order. This makes the sort stable. Scanning forward instead would reverse equal keys and break stability.
Cost
The loops cost n, k, and n steps, so the time is Θ(n + k). The extra space is Θ(n + k), covering the count array and the output array. Counting sort is not in-place. It is efficient when k = O(n). If k is much larger, for example k = n², it takes Θ(n²) time and loses to merge sort.
Radix sort
Radix sort sorts numbers digit by digit, starting from the least significant digit (LSD). Each pass uses a stable sort, usually counting sort.
def radix_sort(a, base=10):
if not a:
return a
exp = 1
biggest = max(a)
while biggest // exp > 0:
digit = lambda x: (x // exp) % base
count = [0] * base
for x in a:
count[digit(x)] += 1
for d in range(1, base):
count[d] += count[d - 1]
out = [0] * len(a)
for x in reversed(a):
d = digit(x)
count[d] -= 1
out[count[d]] = x
a = out
exp *= base
return a
print(radix_sort([170, 45, 75, 90, 802, 24, 2, 66]))The output is [2, 24, 45, 66, 75, 90, 170, 802].
Why stability is required
After sorting by the ones digit, the list is ordered by that digit. The tens pass must not undo this order for numbers that share a tens digit. A stable pass keeps the earlier order among ties. An unstable pass could scramble it, and the final result would be wrong.
Cost
Suppose each key has d digits and each digit takes values in 0 to k-1. Each pass costs Θ(n + k), and there are d passes. The total is Θ(d(n + k)).
For n integers in the range 0 to n^c - 1, use base n. Each key then has d = c digits, and each digit lies in 0 to n-1. The cost is Θ(c · 2n) = Θ(n) for constant c. This is the usual GATE result: radix sort sorts n integers of bounded size in linear time.
If the key range is not bounded by a polynomial in n, d grows with the key size. Then radix sort may be no better than Θ(n log n).
Bucket sort
Bucket sort assumes the keys are spread uniformly over a range, such as real numbers in [0, 1). It makes n buckets and puts key x into bucket ⌊n·x⌋. It then sorts each bucket, usually with insertion sort, and concatenates the buckets.
def bucket_sort(a):
n = len(a)
buckets = [[] for _ in range(n)]
for x in a:
buckets[int(n * x)].append(x)
for b in buckets:
b.sort()
return [x for b in buckets for x in b]
print(bucket_sort([0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12]))The output is [0.12, 0.17, 0.21, 0.26, 0.39, 0.72, 0.78, 0.94].
Cost
With uniform input, each bucket holds a small constant number of keys on average, so sorting all buckets takes expected O(n) time. The total expected time is Θ(n). If all keys land in one bucket, the work becomes the cost of sorting n items in that one bucket. With insertion sort that is O(n²). With a comparison sort such as merge sort per bucket, it is O(n log n). Bucket sort is stable only if the distribution step keeps input order and the per-bucket sort is stable.
Comparison of the three
| Algorithm | Time | Extra space | Stable | Key assumption |
|---|---|---|---|---|
| Counting sort | Θ(n + k) | Θ(n + k) | Yes (backward scan) | Integers in 0 to k-1 |
| Radix sort (LSD) | Θ(d(n + k)) | Θ(n + k) | Yes | d digits, each in 0 to k-1 |
| Bucket sort | Θ(n) expected, O(n²) worst with insertion sort | Θ(n) | Depends on bucket sort | Uniform distribution |
Common errors
- Forgetting that k enters the cost. Counting sort on 10 numbers in the range 0 to 10⁹ is very slow and memory heavy.
- Scanning forward in the placement loop and then claiming stability.
- Using an unstable digit sort inside radix sort.
- Stating that these sorts "beat" Ω(n log n) in general. They beat it only under their input assumptions.
- Calling counting sort in-place. It needs an output array of size n and a count array of size k.
- Starting radix sort from the most significant digit without extra handling. The simple loop above is correct only for least significant digit first.
Exercises
Exercise
Counting sort is run on the array [2, 5, 3, 0, 2, 3, 0, 3] with k = 6. What is the count array after the prefix-sum step?
Show answer
The counts are [2, 0, 2, 3, 0, 1]. The prefix sums give [2, 2, 4, 7, 7, 8]. Each entry is the number of elements less than or equal to that index.
Exercise
You must sort n = 1000 integers, each in the range 0 to 999,999,999. Compare counting sort directly with LSD radix sort in base 1000. Which is better, and what are the costs?
Show answer
Counting sort directly has k = 10⁹, so it costs Θ(n + k) ≈ 10⁹ steps and needs an array of that size. Radix sort in base 1000 has d = 3 digits, since 1000³ = 10⁹, and each pass costs Θ(n + 1000). The total is about 3 × 2000 = 6000 steps. Radix sort is far better.
Exercise
In counting sort, the final loop scans the input from left to right instead of right to left. The code stays correct as a sort. What property is lost, and why does it matter for radix sort?
Show answer
Stability is lost. With a forward scan and decrementing counters, equal keys are placed in reverse order of their appearance. Radix sort relies on each digit pass keeping the order set by earlier passes, so an unstable pass can give a wrongly sorted final result.
Exercise
Bucket sort with n buckets and insertion sort per bucket is run on n keys that all fall into the same bucket. What is the running time?
Show answer
All n keys end up in one bucket, so insertion sort on that bucket takes O(n²) in the worst case. The distribution step adds Θ(n), so the total is O(n²).