Sub topic 2
Stable Counting Sort for Records with Keys
This chapter assumes you know Python lists and functions, Big-O notation, and bit shifts and masks. It also assumes you have seen the histogram version of counting sort from the previous chapter.
Stable Counting Sort for Records with Keys
The histogram version writes bare values back into the array, so any data attached to those values is lost. To sort records, we turn the counts into positions. An exclusive prefix sum replaces counts[v] with the number of keys smaller than v. That number is the first output index for key v. We then walk the input forward and drop each record into the next free slot for its key. Records with equal keys therefore keep their input order, which is what makes the sort stable.
def counting_sort_by_key(items, key, k):
"""Stable sort of items whose key(item) is an integer in 0..k."""
counts = [0] * (k + 1)
for item in items:
counts[key(item)] += 1
total = 0
for v in range(k + 1):
counts[v], total = total, total + counts[v]
out = [None] * len(items)
for item in items:
kv = key(item)
out[counts[kv]] = item
counts[kv] += 1
return out
people = [("ana", 2), ("bo", 1), ("cy", 2), ("di", 0)]
print(counting_sort_by_key(people, lambda p: p[1], 2))
# [('di', 0), ('bo', 1), ('ana', 2), ('cy', 2)]Counting Sort Cost: O(n + k) and the Range Problem
The counting pass and the placement pass each take O(n). The prefix-sum pass takes O(k). Total time and extra space are O(n + k).
| Situation | Effect |
|---|---|
| k ≤ n (ages, grades) | Linear and fast |
| k ≫ n (32-bit IDs) | The 4-billion-entry count array dominates |
Breaking Keys into Digits
A large key can be split into d digits in base b, where b is called the radix. With b = 256, each digit is one byte: (x >> shift) & 255. Each digit lies in 0..b−1, so it is a small range that counting sort handles well.
LSD Radix Sort: Least Significant Digit First
LSD radix sort runs one stable counting sort per digit, starting with the lowest digit. When a later pass finds two equal digits, stability keeps the order that the earlier passes set up. The total cost is O(d(n + b)).
The code below calls counting_sort_by_key from the earlier block, so run both blocks together.
def radix_sort_lsd(a, bits_per_digit=8):
"""Sort non-negative integers using LSD radix sort."""
if not a:
return []
mask = (1 << bits_per_digit) - 1
max_val = max(a)
out = list(a)
shift = 0
while (max_val >> shift) > 0:
out = counting_sort_by_key(out, lambda x: (x >> shift) & mask, mask)
shift += bits_per_digit
return out
print(radix_sort_lsd([170, 45, 75, 90, 802, 24, 2, 66]))
# [2, 24, 45, 66, 75, 90, 170, 802]Exercise
How many counting-sort passes does radixsortlsd make on 32-bit keys with bitsperdigit=8, assuming max_val uses all 32 bits? What is the cost of each pass?
Show answer
It makes 4 passes, one for each byte. Each pass costs O(n + 256), so the total is O(4(n + 256)), which is O(n).
Exercise
Why would LSD radix sort give wrong results if each pass used an unstable sort?
Show answer
A later pass could reorder keys whose current digits are equal. That would destroy the order the lower digits had already established.