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

The limits of sorting

Why no comparison sort can beat N log N: counting orderings, decision trees, and log N! ≈ N log N; how close real sorts come; lower bounds by reduction; and a summary of every sort in this unit.

CS61B
Sorting and Algorithmic Bounds · Textbook Ch. 32, Ch. 34
Swift book
Closures
Documentation
sort() · sorted()

Merge sort, heapsort, and quicksort all make about N log N comparisons. Could a cleverer algorithm make fewer, say N log log N, or even N? This lesson, following CS61B’s lecture on sorting and algorithmic bounds, proves that no sort that works by comparing items can: Ω(N log N) comparisons are necessary in the worst case. It is one of the few lower bounds in computer science that can be proved in a few lines.

A guessing game

CS61B starts with a puzzle. A puppy, a cat, and a dog are lined up in some order you cannot see. You may ask questions of the form “is the puppy to the left of the cat?”, and get yes or no. How many questions do you need to know the whole order?

There are 3! = 6 possible orders. Each answer at best halves the number of orders still possible: after one question, at least 3 remain in the worse case; after two, at least 2. So three questions are needed in the worst case, and three suffice.

Sorting is the same game with N items: there are N! possible orders, and each comparison is a yes-or-no question.

Decision trees

Any comparison sort can be drawn as a decision tree: each internal node is a comparison, each branch an answer, and each leaf a final order. Running the sort on an input follows one path from the root to a leaf.

  • The tree must have at least N! leaves, one for each possible input order, since each order must be rearranged differently.
  • A binary tree of height h has at most 2ʰ leaves.
  • So 2ʰ ≥ N!, and the height, the worst-case number of comparisons, is at least log₂ N!.

And log₂ N! grows like N log N: N! ≥ (N/2)^(N/2), because its larger half of factors is each at least N/2, so log₂ N! ≥ (N/2) log₂(N/2), which is Ω(N log N). (Stirling’s formula gives the precise value, log₂ N! ≈ N log₂ N − 1.44 N.)

Every comparison sort needs Ω(N log N) comparisons in the worst case. Merge sort and heapsort are therefore asymptotically optimal: no comparison sort beats them by more than a constant factor.

import Foundation

func log2Factorial(_ n: Int) -> Double {
    (1...n).map { log2(Double($0)) }.reduce(0, +)
}

for n in [3, 10, 1_000] {
    print(n, Int(log2Factorial(n).rounded(.up)), Int((Double(n) * log2(Double(n))).rounded()))
}
// 3 3 5
// 10 22 33
// 1000 8530 9966

For the puppy, cat, and dog, ⌈log₂ 6⌉ = 3, as the puzzle found. For 1,000 items, at least 8,530 comparisons are needed in the worst case, close to N log₂ N.

What would Swift print?

var comparisons = 0
func less(_ a: Int, _ b: Int) -> Bool {
    comparisons += 1
    return a < b
}
func sort3(_ a: Int, _ b: Int, _ c: Int) -> [Int] {
    var (x, y, z) = (a, b, c)
    if less(y, x) { swap(&x, &y) }
    if less(z, y) { swap(&y, &z) }
    if less(y, x) { swap(&x, &y) }
    return [x, y, z]
}
print(sort3(3, 1, 2), sort3(2, 3, 1), comparisons)

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

Show answer and explanation

Answer[1, 2, 3] [1, 2, 3] 6

Three comparisons per call, whatever the input: exactly the lower bound for three items, ⌈log₂ 3!⌉ = 3. This is a tiny sorting network: a fixed sequence of compare-and-swap steps, which hardware can run in parallel.

How close real sorts come

Swift’s sorted() can be measured by counting calls to the comparator. On one run, for random arrays:

N Lower bound ⌈log₂ N!⌉ sorted() N log₂ N
100 525 about 1,400 664
1,000 8,530 about 20,600 9,966
100,000 1,516,705 about 2,385,000 1,660,964

Swift’s sort makes a small constant factor more comparisons than the bound, partly because it sorts short runs with insertion sort (Lesson 54), which is fast in practice despite comparing more. And on already sorted input it makes exactly N − 1 comparisons: the lower bound is about the worst case, not every input.

What the bound does not say

The argument assumed that the only way to learn about the items is to compare them. Sorts that look at the items themselves can do better. If the items are integers between 0 and 9, count how many of each there are and write them out: that is linear, and no comparison is made. Lesson 57 builds such sorts, radix sorts, which beat N log N whenever the keys are short.

The bound is also about comparisons, not time. An algorithm that makes few comparisons but much other work is not fast.

Lower bounds by reduction

Lesson 47 used reductions to solve problems. They also prove problems hard. Suppose some algorithm could find the closest pair among N numbers on a line faster than N log N using comparisons. Then element distinctness, deciding whether any two of N items are equal, which is known to need Ω(N log N) comparisons, could be solved as fast: the items are distinct exactly when the closest pair is not at distance 0. So the closest pair problem needs Ω(N log N) too. The pattern: if a known-hard problem reduces cheaply to a new one, the new one is at least as hard.

Every sort, compared

CS61B ends its sorting unit with a summary. With N items:

Sort Worst time Average time Memory Stable Notes
Selection Θ(N²) Θ(N²) Θ(1) no few swaps
Insertion Θ(N²) Θ(N²) Θ(1) yes Θ(N + inversions): fast when nearly sorted, or small
Heapsort Θ(N log N) Θ(N log N) Θ(1) no poor cache behavior
Merge sort Θ(N log N) Θ(N log N) Θ(N) yes good for huge or streamed data
Quicksort (random pivot) Θ(N²), with vanishing probability Θ(N log N) Θ(log N) stack no fastest in practice among these
Radix sorts (Lesson 57) Θ(W N) for W-digit keys Θ(W N) Θ(N + R) LSD: yes no comparisons
Swift’s sort O(N log N) O(N log N) Θ(N) yes merge-based, detects sorted runs

Put the lines in order

Put the lines in order so the program prints 6.

  1. }
  2. for k in 1...items {
  3. orders *= k
  4. print(orders)
  5. var orders = 1
  6. let items = 3

Show the correct program
var orders = 1
let items = 3
for k in 1...items {
    orders *= k
}
print(orders)

Lab 55: The limits of sorting

Q0: What would Swift print?

What would Swift print?

var leaves = 1
var height = 0
while leaves < 24 {
    leaves *= 2
    height += 1
}
print(height)

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

Show answer and explanation

Answer5

A decision tree for 4 items needs 4! = 24 leaves, and a binary tree of height 4 has at most 16, so the height must be at least 5: sorting four items needs five comparisons in the worst case, and five suffice.

Q1: Counting comparisons

Write comparisonsUsed(_:), which returns how many times a sort calls its comparator on an array, and use it to check that sorted(by:) never uses fewer than ⌈log₂ N!⌉ comparisons in the worst of 20 random shuffles, for N from 2 to 12.

Show solution
import Foundation

func comparisonsUsed(_ values: [Int]) -> Int {
    var count = 0
    _ = values.sorted { count += 1; return $0 < $1 }
    return count
}

func lowerBound(_ n: Int) -> Int {
    Int((1...n).map { log2(Double($0)) }.reduce(0, +).rounded(.up))
}

var generator = SystemRandomNumberGenerator()
for n in 2...12 {
    let worst = (0..<20).map { _ in comparisonsUsed(Array(0..<n).shuffled(using: &generator)) }.max()!
    assert(worst >= lowerBound(n) || n > 8)
}
assert(comparisonsUsed(Array(0..<100)) == 99)       // sorted input: one pass

For small N, twenty shuffles usually include an input near the worst case, so the worst observed count reaches the bound. For larger N, twenty samples may all miss the worst case, which is why the check only insists for N up to 8: the bound says the worst input needs that many comparisons, not that every input does, and the sorted input at the end needs only 99.

Q2: Maximum and minimum together

Finding the maximum takes N − 1 comparisons, and so does the minimum: 2N − 2 for both. Do it in about 3N/2: compare items in pairs, then compare the larger of each pair with the current maximum and the smaller with the current minimum.

Show solution
var comparisons = 0
func less(_ a: Int, _ b: Int) -> Bool { comparisons += 1; return a < b }

func minAndMax(_ values: [Int]) -> (min: Int, max: Int)? {
    guard var low = values.first else { return nil }
    var high = low
    var i = values.count % 2 == 0 ? 0 : 1          // odd count: the first item started both
    if values.count % 2 == 0 {
        (low, high) = less(values[1], values[0]) ? (values[1], values[0]) : (values[0], values[1])
        i = 2
    }
    while i + 1 < values.count {
        let (small, large) = less(values[i + 1], values[i]) ? (values[i + 1], values[i]) : (values[i], values[i + 1])
        if less(small, low) { low = small }
        if less(high, large) { high = large }
        i += 2
    }
    return (low, high)
}

let values = (0..<1_000).map { ($0 * 7919) % 1_000 }
comparisons = 0
let result = minAndMax(values)!
assert(result.min == 0 && result.max == 999)
assert(comparisons <= 3 * 1_000 / 2)
assert(minAndMax([5])! == (5, 5) && minAndMax([]) == nil)

Each pair costs three comparisons for two items, instead of four. An adversary argument, similar to the decision tree, shows that ⌈3N/2⌉ − 2 comparisons are also necessary, so this is optimal.

Q3 (optional): Distinctness by sorting

Element distinctness needs Ω(N log N) comparisons, and sorting solves it in O(N log N). Write it that way, and then note what changes when the items are Hashable, not just Comparable.

Show solution
func allDistinct<T: Comparable>(_ values: [T]) -> Bool {
    let sorted = values.sorted()
    return zip(sorted, sorted.dropFirst()).allSatisfy { $0 != $1 }
}

func allDistinctByHashing<T: Hashable>(_ values: [T]) -> Bool {
    var seen = Set<T>()
    return values.allSatisfy { seen.insert($0).inserted }
}

assert(allDistinct([3, 1, 4, 5]) && !allDistinct([3, 1, 4, 1]))
assert(allDistinctByHashing([3, 1, 4, 5]) && !allDistinctByHashing(["a", "b", "a"]))

With hashing, distinctness takes expected Θ(N): the Ω(N log N) bound applies only to algorithms that learn about items by comparing them. Hashing looks at the items themselves, like radix sort, and escapes the bound, at the price of a guarantee that holds only on average.

What’s next

Next lesson: radix sorts, which sort without comparing, and beat N log N.