Tutorial outline

Unit 1

  1. 01Getting started
  2. 02Names and functions
  3. 03Control
  4. 04Higher-order functions
  5. 05Environments and closures
  6. 06Functional abstraction
  7. 07Recursion
  8. 08Tree recursion
  1. D0Getting started
  2. D1Control and environment diagrams
  3. HW1Functions and control
  4. D2Higher-order functions
  5. HW2Higher-order functions
  6. P1Hog
  7. D3Recursion
  8. D4Tree recursion
  9. HW3Recursion

Unit 2

  1. 09Sequences
  2. 10Dictionaries, sets, and tuples
  3. 11Optionals
  4. 12Structures and enumerations
  5. 13Linked lists and trees
  6. 14Mutation and value semantics
  7. 15Classes and inheritance
  8. 16Protocols and generics
  9. 17Iterators and lazy sequences
  10. 18Efficiency and memoization
  1. HW4Sequences and containers
  2. P2Cats
  3. D5Trees
  4. HW5Recursive data and mutation
  5. D6Objects and classes
  6. HW6Classes and interfaces
  7. P3Ants vs. SomeBees
  8. D7Iterators and efficiency
  9. HW7Lazy sequences and efficiency

Unit 3

  1. 19Algebraic data types and pattern matching
  2. 20Writing an interpreter
  3. 21Error handling
  4. 22Concurrency with async and await
  5. 23Testing
  6. 24Building a Swift package
  1. D8Algebraic data types
  2. HW8Pattern matching
  3. D9Interpreters
  4. HW9Interpreters and errors
  5. P4Scheme
  6. D10Concurrency
  7. D11Testing
  8. HW10Concurrency and testing

Unit 4

  1. 25References, identity, and memory
  2. 26Drawing with SwiftUI
  3. 27Testing data structures
  4. 28IntLists and SLLists
  5. 29Doubly linked lists and deques
  6. 30Arrays from scratch
  7. 31Interface and implementation inheritance
  8. 32Iteration, equality, and ordering
  9. 33Copy-on-write collections
  1. D12Swift review
  2. D13References, classes, and arrays
  3. HW11Swift warm-up
  4. P5Particle Simulator
  5. D14IntLists and SLLists
  6. HW12IntLists
  7. P6LinkedListDeque
  8. D15DLLists, default implementations, and array lists
  9. P7ArrayDeque
  10. D16Comparables and iterators
  11. HW13Review I

Unit 5

  1. 34Asymptotic analysis
  2. 35Disjoint sets
  3. 36Analyzing recursion
  4. 37Amortized analysis and the limits of big O
  5. 38Sets, maps, and binary search trees
  6. 39B-trees
  7. 40Left-leaning red-black trees
  8. 41Heaps and priority queues
  1. D17Asymptotics and disjoint sets
  2. P8Percolation
  3. D18Asymptotics II
  4. HW14Asymptotic analysis
  5. D19BSTs, B-trees, and LLRBs
  6. HW15BSTMap

Unit 6

  1. 42Data-driven apps with SwiftUI
  2. 43Tree and graph traversals
  3. 44Graph implementations
  4. 45Shortest paths: Dijkstra and A*
  5. 46Minimum spanning trees
  6. 47DAGs, topological sort, and reductions
  1. D20Tree traversals and graphs
  2. P9NGordNet
  3. D21Shortest paths and MSTs

Unit 7

  1. 48Hash tables
  2. 49Hash functions
  3. 50Tries and prefix operations
  4. 51Software engineering: managing complexity
  5. 52Games with SwiftUI
  6. 53Designing a world
  7. 54Basic sorts
  8. 55Quicksort and selection
  9. 56The limits of sorting
  10. 57Radix sorts
  11. 58Compression and complexity
  12. 59Computing, society, and what comes next
  1. D22Hashing and tries
  2. HW16Review II
  3. D23Hashing and tries, revisited
  4. P10Build Your Own World
  5. D24Sorting
  6. HW17HashMap
  7. D25Sorting II
  8. HW18LLRB set
  9. HW19Final review

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

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:

  1. Count how many items have each key.
  2. Turn the counts into starting positions with a running sum: the first item with key k goes after all the items with smaller keys.
  3. 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) })

Type Error if running it would crash. For several lines of output, put each on its own line.

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].

  1. let grades = [2, 5, 0, 2]
  2. var counts = Array(repeating: 0, count: grades.max()! + 1)
  3. print(sorted)
  4. let sorted = counts.indices.flatMap { Array(repeating: $0, count: counts[$0]) }
  5. 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)

Type Error if running it would crash. For several lines of output, put each on its own line.

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.