Radix sorts
Sorting without comparisons: counting sort with prefix sums, least-significant-digit radix sort for fixed-width keys using bit shifts and masks, most-significant-digit radix sort for strings, and when they beat N log N.
- CS61B
- Radix Sorts · Textbook Ch. 33
- Swift book
- Advanced Operators
Lesson 56 proved that sorting by comparisons needs Ω(N log N) steps. Its escape clause: an algorithm that looks inside the keys, at their digits or characters, is not bound by it. This lesson, following CS61B’s radix sort lecture, builds such sorts, which run in linear time on keys of fixed length.
Counting sort
Suppose every key is one of R values, 0 to R − 1: grades from 0 to 100, letters from a to z, bytes from 0 to 255. Then:
- Count how many items have each key.
- Turn the counts into starting positions with a running sum: the first item with key k goes after all the items with smaller keys.
- Place each item at its key’s next position, in the order the items came.
func countingSort<T>(_ items: [T], keyCount: Int, key: (T) -> Int) -> [T] {
var counts = Array(repeating: 0, count: keyCount)
for item in items {
counts[key(item)] += 1
}
var starts = Array(repeating: 0, count: keyCount)
for k in 1..<keyCount {
starts[k] = starts[k - 1] + counts[k - 1]
}
var result: [T?] = Array(repeating: nil, count: items.count)
for item in items {
result[starts[key(item)]] = item
starts[key(item)] += 1
}
return result.map { $0! }
}
let people = [("Ada", 3), ("Bo", 1), ("Cy", 3), ("Di", 0), ("Ed", 1)]
let byGroup = countingSort(people, keyCount: 4) { $0.1 }
print(byGroup.map(\.0)) // ["Di", "Bo", "Ed", "Ada", "Cy"]
No item is ever compared with another. The work is Θ(N + R): one pass to count, one over the R keys to sum, and one to place. When R is small compared with N, that is linear.
Counting sort is stable: items with the same key are placed in the order they were read, as Bo before Ed and Ada before Cy show. That property is what makes the next sort possible.
LSD radix sort
Keys like 32-bit integers have far too many possible values for a counting array. But each key is a sequence of digits: in base 256, a 32-bit integer is four bytes. Least-significant-digit (LSD) radix sort counting-sorts by the last digit, then by the second-to-last, and so on, finishing with the first:
start by last digit by middle digit by first digit
329 720 720 329
457 355 329 355
657 436 436 436
839 → 457 → 839 → 457
436 657 355 657
720 329 457 720
355 839 657 839
After sorting by the last digit, then stably by the middle one, items with the same middle digit stay in order of their last digits: the last two digits are now sorted. Each pass extends the sorted suffix by one digit, and after all W digits, the keys are sorted. Stability is essential: an unstable pass would scramble the work of the previous ones.
For integers, digits come from bit operations (the Swift book’s advanced operators
chapter): shifting right by 8 × d bits moves byte d to the bottom, and masking with
& 0xFF keeps only that byte.
func radixSort(_ values: [UInt32]) -> [UInt32] {
var items = values
for d in 0..<4 { // bytes, least significant first
let shift = UInt32(8 * d)
var counts = Array(repeating: 0, count: 257)
for v in items {
counts[Int((v >> shift) & 0xFF) + 1] += 1
}
for k in 1...256 {
counts[k] += counts[k - 1] // counts[b]: where byte b starts
}
var next = Array(repeating: UInt32(0), count: items.count)
for v in items {
let b = Int((v >> shift) & 0xFF)
next[counts[b]] = v
counts[b] += 1
}
items = next
}
return items
}
let values: [UInt32] = [329, 457, 657, 839, 436, 720, 355, 4_000_000_000, 7, 65_536]
print(radixSort(values) == values.sorted()) // true
Storing each count one slot to the right, in counts[b + 1], makes the running sum
produce starting positions directly. The cost is Θ(W(N + R)) for W digits of R values:
here 4 passes over N items plus 4 × 256 counters, linear in N for fixed-width keys.
What would Swift print?
let value: UInt32 = 0x12345678
let bytes = (0..<4).map { (value >> UInt32(8 * $0)) & 0xFF }
print(bytes.map { String($0, radix: 16) })Show answer and explanation
Answer["78", "56", "34", "12"]
Shifting right by 0, 8, 16, and 24 bits brings each byte in turn to the bottom, and
& 0xFF keeps only the lowest 8 bits. Hexadecimal makes the bytes visible: the least
significant, 78, comes first, which is the order LSD radix sort processes them.
MSD radix sort
LSD radix sort needs keys of the same length. Strings are not. Most-significant-digit (MSD) radix sort goes the other way: counting-sort by the first character, then recursively sort each group by the next character. Strings that run out of characters come first in their group, since “car” precedes “card”.
MSD is natural for strings and can stop early: once a group has one string, it is done, so it often examines only the characters needed to tell strings apart. But it recurses into many small groups, each needing its own count array, so practical versions switch to insertion sort for small groups.
When radix sort wins
For N integers of W digits, radix sort is Θ(W N), and a comparison sort Θ(N log N). With fixed-width keys, W is a constant, so radix sort is asymptotically faster. In practice:
- For large arrays of fixed-width integers, such as a million 32-bit values, LSD radix sort is usually faster than any comparison sort.
- For short arrays, the counting arrays’ setup dominates, and comparison sorts win.
- For long keys, where W is comparable to log N, the advantage disappears.
- Radix sort needs keys that break into digits. A comparator, such as “by distance from the origin”, gives a comparison sort nothing more, and a radix sort nothing to use.
Radix sort is also the oldest sort here: machines that sorted punched cards, one column at a time, from the 1890 US census onward, were LSD radix sorters.
Put the lines in order
Put the lines in order so the program prints [0, 2, 2, 5].
let grades = [2, 5, 0, 2]var counts = Array(repeating: 0, count: grades.max()! + 1)print(sorted)let sorted = counts.indices.flatMap { Array(repeating: $0, count: counts[$0]) }for g in grades { counts[g] += 1 }
Show the correct program
let grades = [2, 5, 0, 2]
var counts = Array(repeating: 0, count: grades.max()! + 1)
for g in grades { counts[g] += 1 }
let sorted = counts.indices.flatMap { Array(repeating: $0, count: counts[$0]) }
print(sorted)Lab 56: Radix sorts
Q0: What would Swift print?
What would Swift print?
let counts = [2, 0, 3, 1]
var starts = [0, 0, 0, 0]
for k in 1..<4 {
starts[k] = starts[k - 1] + counts[k - 1]
}
print(starts)Show answer and explanation
Answer[0, 2, 2, 5]
Key 0’s two items take positions 0 and 1, so key 1 starts at 2. Key 1 has no items, so key 2 also starts at 2, and its three items take 2 to 4; key 3 starts at 5.
Q1: Sorting words by length
Use countingSort to sort words by length, stably, and check that words of equal
length keep their original order. What is R here?
Show solution
func countingSort<T>(_ items: [T], keyCount: Int, key: (T) -> Int) -> [T] {
var counts = Array(repeating: 0, count: keyCount + 1)
for item in items { counts[key(item) + 1] += 1 }
for k in 1...keyCount { counts[k] += counts[k - 1] }
var result: [T?] = Array(repeating: nil, count: items.count)
for item in items {
result[counts[key(item)]] = item
counts[key(item)] += 1
}
return result.map { $0! }
}
let words = ["banana", "fig", "kiwi", "apple", "pear", "yam", "cherry"]
let longest = words.map(\.count).max()!
let sorted = countingSort(words, keyCount: longest + 1) { $0.count }
assert(sorted == ["fig", "yam", "kiwi", "pear", "apple", "banana", "cherry"])R is one more than the longest word’s length, here 7. Words of the same length stay in their original order: fig before yam, kiwi before pear, banana before cherry.
Q2: Signed integers
Extend the LSD radix sort to [Int32], handling negative numbers by flipping the sign
bit before sorting and after, and test it against sorted() on random values.
Show solution
func radixSort(_ values: [UInt32]) -> [UInt32] {
var items = values
for d in 0..<4 {
let shift = UInt32(8 * d)
var counts = Array(repeating: 0, count: 257)
for v in items { counts[Int((v >> shift) & 0xFF) + 1] += 1 }
for k in 1...256 { counts[k] += counts[k - 1] }
var next = Array(repeating: UInt32(0), count: items.count)
for v in items {
let b = Int((v >> shift) & 0xFF)
next[counts[b]] = v
counts[b] += 1
}
items = next
}
return items
}
func radixSort(_ values: [Int32]) -> [Int32] {
let flipped = values.map { UInt32(bitPattern: $0) ^ 0x8000_0000 }
return radixSort(flipped).map { Int32(bitPattern: $0 ^ 0x8000_0000) }
}
var generator = SystemRandomNumberGenerator()
let values = (0..<10_000).map { _ in Int32.random(in: .min ... .max, using: &generator) }
assert(radixSort(values) == values.sorted())
assert(radixSort([3, -1, 0, Int32.min, Int32.max, -1]) == [Int32.min, -1, -1, 0, 3, Int32.max])In two’s complement, negative numbers have the top bit set, so read as unsigned they look larger than positives. Flipping that bit swaps the two halves of the range into the right order.
Q3: MSD radix sort for strings
Write msdSort(_:) for strings of lowercase ASCII letters, using counting sort by the
character at position d, recursing into each group with d + 1, and putting strings that
end at d first. Test it against sorted().
Show solution
func msdSort(_ words: [String]) -> [String] {
let bytes = words.map { Array($0.utf8) }
func sort(_ group: [[UInt8]], _ d: Int) -> [[UInt8]] {
guard group.count > 1 else { return group }
// Bucket 0: words that end before position d; buckets 1…26: a…z.
var buckets = Array(repeating: [[UInt8]](), count: 27)
for word in group {
let bucket = d < word.count ? Int(word[d] - UInt8(ascii: "a")) + 1 : 0
buckets[bucket].append(word)
}
return buckets[0] + buckets[1...].flatMap { sort($0, d + 1) }
}
return sort(bytes, 0).map { String(decoding: $0, as: UTF8.self) }
}
let words = ["card", "car", "cat", "a", "", "cart", "dog", "ca", "do"]
assert(msdSort(words) == words.sorted())
var generator = SystemRandomNumberGenerator()
let letters = Array("abcdefghijklmnopqrstuvwxyz")
let random = (0..<2_000).map { _ in String((0..<Int.random(in: 0...6, using: &generator)).map { _ in letters.randomElement(using: &generator)! }) }
assert(msdSort(random) == random.sorted())The empty bucket, words that have ended, comes before a, which is exactly the rule
that makes a prefix sort before its extensions. A group of one word needs no more work,
so words that differ early are finished after a few characters.
Q4 (optional): Which is faster?
Time radixSort against sorted() on arrays of random UInt32 values of sizes 10 to
1,000,000, in a release build, and find where radix sort starts to win.
Show solution
let clock = ContinuousClock()
var generator = SystemRandomNumberGenerator()
for n in [10, 100, 1_000, 100_000, 1_000_000] {
let values = (0..<n).map { _ in UInt32.random(in: 0 ... .max, using: &generator) }
let radix = (0..<3).map { _ in clock.measure { _ = radixSort(values) } }.min()!
let library = (0..<3).map { _ in clock.measure { _ = values.sorted() } }.min()!
print(n, radix, library)
}Build it with swiftc -O and run it. On the machine this lesson was written on, the
library sort was faster for 10 and 50 items, where radix sort’s four passes over 257
counters dominate; they were about even at 100; and from there radix sort pulled ahead
by a growing factor: about 8 times faster at 1,000 items, and about 20 times at a
million, since its cost grows linearly while the comparison sort’s grows like N log N.
The exact crossover depends on the machine, which is the lesson: measure.
What’s next
Next lesson: compression, making data smaller, and a first look at the questions of complexity theory.