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

Analyzing recursion

Orders of growth for code that is not two simple loops: geometric sums, dependent loops, call trees for recursive functions, binary search, merge sort, and a table of common recurrences.

CS61B
Asymptotics II · Textbook Ch. 12
Swift book
Functions

Lesson 34 found orders of growth for loops that run a fixed number of times. Most interesting code is not like that: loops whose bounds grow or shrink geometrically, and functions that call themselves. This lesson, following CS61B’s second asymptotics lecture, gives a method for both. There is no single formula to apply; the method is to find the total work by adding it up in a smart order, and it rests on two sums worth knowing by heart.

Two sums

The arithmetic sum. 1 + 2 + 3 + … + N = N(N + 1)/2, which is Θ(N²). Lesson 34’s dup1 was this sum.

The geometric sum. 1 + 2 + 4 + 8 + … + N = 2N − 1 when N is a power of two, which is Θ(N). Each term is as large as all the previous ones together, so the whole sum is less than twice its last term.

Almost every analysis in this course reduces to one of these two.

Loops that are not simple

Consider a loop whose bound doubles:

var work = 0
let n = 64
var i = 1
while i <= n {
    for _ in 0..<i {
        work += 1
    }
    i *= 2
}
print(work)   // 127

It is two nested loops, but it is not Θ(N²). The inner loop runs 1, 2, 4, …, 64 times, a geometric sum: 127 = 2 · 64 − 1. The work is Θ(N).

The mistake to avoid is multiplying the number of outer iterations by the largest inner count. There are log₂ N + 1 outer iterations, and the largest inner loop has N steps, so the answer is at most N log N, but that bound is not tight. Add up what actually happens instead.

What would Swift print?

var work = 0
let n = 100
var i = n
while i > 0 {
    for _ in 0..<i {
        work += 1
    }
    i /= 2
}
print(work)

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

Show answer and explanation

Answer197

The inner loop runs 100, 50, 25, 12, 6, 3, and 1 times: 197 in all, just under 2N. Halving from the top is the same geometric sum as doubling from the bottom, so this is Θ(N) too.

Recursive functions

For a recursive function, draw the call tree: each call is a node, with the calls it makes as its children. The total work is the work done in every node, added up. Count level by level:

var calls = 0

func f(_ n: Int) -> Int {
    calls += 1
    return n <= 1 ? 1 : f(n - 1) + f(n - 1)
}

_ = f(10)
print(calls)   // 1023

Each call makes two calls on a problem one smaller, so level k of the tree has 2ᵏ nodes, and there are N levels: 1 + 2 + 4 + … + 2ᴺ⁻¹ = 2ᴺ − 1 calls, each doing constant work. f is Θ(2ᴺ). Computing f(n - 1) once and doubling it would make it Θ(N).

Recurrences

The same reasoning can be written as a recurrence: an equation for the running time T(N) in terms of the time for smaller inputs. For f,

T(N) = 2 T(N − 1) + c, T(1) = c

where c is the constant work in one call. Expanding it a few times shows the pattern: T(N) = 2(2 T(N − 2) + c) + c = 4 T(N − 2) + 3c = … = (2ᴺ − 1) c.

Lesson 18’s binary search halves the range on every step. Its recurrence is

T(N) = T(N / 2) + c

and each expansion adds one c while halving N, so after log₂ N expansions the range is a single item: T(N) is Θ(log N). Counting the exact number of steps confirms it:

func steps(toSearch n: Int) -> Int {
    var low = 0
    var high = n - 1
    var count = 0
    while low <= high {           // an unsuccessful search, always going right
        count += 1
        let middle = (low + high) / 2
        low = middle + 1
    }
    return count
}

print((1...8).map { steps(toSearch: 1 << $0) })   // [2, 3, 4, 5, 6, 7, 8, 9]

Doubling N adds exactly one step: for N = 2ᵏ, the search takes k + 1 steps. A million items take 20 steps.

Merge sort

Merge sort sorts an array by splitting it in half, sorting each half recursively, and merging the two sorted halves. Merging is the key: two sorted arrays can be combined into one by repeatedly taking the smaller of their two first items, in time proportional to the total length.

var comparisons = 0

func merge(_ a: ArraySlice<Int>, _ b: ArraySlice<Int>) -> [Int] {
    var result: [Int] = []
    result.reserveCapacity(a.count + b.count)
    var i = a.startIndex
    var j = b.startIndex
    while i < a.endIndex && j < b.endIndex {
        comparisons += 1
        if a[i] <= b[j] {
            result.append(a[i])
            i += 1
        } else {
            result.append(b[j])
            j += 1
        }
    }
    return result + a[i...] + b[j...]
}

func mergeSort(_ values: ArraySlice<Int>) -> [Int] {
    guard values.count > 1 else {
        return Array(values)
    }
    let middle = values.startIndex + values.count / 2
    let left = mergeSort(values[..<middle])
    let right = mergeSort(values[middle...])
    return merge(left[...], right[...])
}

let values = (0..<1024).map { ($0 * 389) % 1024 }     // a shuffled order
let sorted = mergeSort(values[...])
print(sorted == values.sorted(), comparisons)   // true 9173

Slices keep the indices of the array they came from (Lesson 8), which is why the code uses startIndex rather than 0. Now the analysis:

T(N) = 2 T(N / 2) + cN

Draw the tree. The top level merges N items. The next level has two calls, each merging N/2 items: N in all. Every level does N work in total, and halving from N down to 1 takes log₂ N levels. So merge sort is Θ(N log N). For N = 1024, that bound is 10,240 comparisons, and the actual count, 9,173, is just below it: each merge can stop early when one side runs out.

N log N is far better than N²: for a million items, about 20 million steps instead of a trillion. Lessons 54 to 56 return to sorting, and prove that no comparison sort can do better than N log N.

A table of recurrences

The patterns above come up constantly. With T(1) constant:

Recurrence Solution Example
T(N) = T(N/2) + 1 Θ(log N) binary search
T(N) = T(N − 1) + 1 Θ(N) walking a linked list recursively
T(N) = T(N/2) + N Θ(N) the halving loop above
T(N) = 2T(N/2) + 1 Θ(N) visiting every node of a balanced tree
T(N) = 2T(N/2) + N Θ(N log N) merge sort
T(N) = T(N − 1) + N Θ(N²) selection sort, recursively
T(N) = 2T(N − 1) + 1 Θ(2ᴺ) the doubling f above

When a recurrence is not in the table, draw its tree: count the nodes on each level, the work in each node, and the number of levels, and add it up.

Put the lines in order

Put the lines in order so the program prints 15.

  1. }
  2. visit(3)
  3. calls += 1
  4. visit(depth - 1)
  5. var calls = 0
  6. func visit(_ depth: Int) {
  7. print(calls)
  8. guard depth > 0 else { return }
  9. visit(depth - 1)

Show the correct program
var calls = 0
func visit(_ depth: Int) {
    calls += 1
    guard depth > 0 else { return }
    visit(depth - 1)
    visit(depth - 1)
}
visit(3)
print(calls)

Lab 35: Analyzing recursion

Q0: What would Swift print?

What would Swift print?

var calls = 0
func g(_ n: Int) {
    calls += 1
    if n > 1 {
        g(n / 2)
        g(n / 2)
        g(n / 2)
    }
}
g(8)
print(calls)

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

Show answer and explanation

Answer40

Level by level: 1 call for 8, 3 calls for 4, 9 for 2, and 27 for 1, which make no further calls. 1 + 3 + 9 + 27 = 40. In general T(N) = 3T(N/2) + 1, which is Θ(N^log₂3), about Θ(N^1.585).

Q1: Orders of growth

Give the order of growth of each function, in terms of N, and check each by counting.

func a(_ n: Int) { var i = 1; while i < n { for _ in 0..<n { work() }; i *= 2 } }
func b(_ n: Int) { for i in 1...n { var j = 1; while j < i { work(); j *= 2 } } }
func c(_ n: Int) { if n > 1 { work(); c(n - 1); c(n - 1) } }
func d(_ n: Int) { if n > 1 { for _ in 0..<n { work() }; d(n / 2) } }
Show solution
  • a: the outer loop runs about log₂ N times, and the inner loop is N every time, so Θ(N log N). Here multiplying is right, because the inner loop does not change.
  • b: iteration i does about log₂ i work, and log₂ 1 + … + log₂ N = log₂ N!, which is Θ(N log N): half of the terms are at least log₂(N/2).
  • c: T(N) = 2T(N − 1) + 1, Θ(2ᴺ).
  • d: T(N) = T(N/2) + N, a geometric sum, Θ(N).
var count = 0
func work() { count += 1 }

func a(_ n: Int) { var i = 1; while i < n { for _ in 0..<n { work() }; i *= 2 } }
func b(_ n: Int) { for i in 1...n { var j = 1; while j < i { work(); j *= 2 } } }
func c(_ n: Int) { if n > 1 { work(); c(n - 1); c(n - 1) } }
func d(_ n: Int) { if n > 1 { for _ in 0..<n { work() }; d(n / 2) } }

func counted(_ f: (Int) -> Void, _ n: Int) -> Int {
    count = 0
    f(n)
    return count
}

assert(counted(a, 1024) == 1024 * 10)
assert(counted(c, 11) == 1023)
assert(counted(d, 1024) == 2046)
let ratio = Double(counted(b, 4096)) / Double(counted(b, 2048))
assert(ratio > 2 && ratio < 2.3)   // a little more than doubling: N log N

For b, a ratio a little over 2 when N doubles is the fingerprint of N log N: doubling N doubles it, then log N adds a little more.

Q2: A recurrence from code

Write the recurrence for the number of calls this function makes, solve it, and check your answer for several values of N.

func h(_ n: Int) -> Int {
    n <= 2 ? 1 : h(n - 1) + h(n - 3)
}
Show solution

C(N) = 1 + C(N − 1) + C(N − 3) for N > 2, and C(N) = 1 for N ≤ 2. It grows exponentially: C(N) is roughly r^N, where r ≈ 1.4656 is the real root of r³ = r² + 1. It is slower than the doubling f, but still Θ(rᴺ), exponential.

var calls = 0
func h(_ n: Int) -> Int {
    calls += 1
    return n <= 2 ? 1 : h(n - 1) + h(n - 3)
}

func predicted(_ n: Int) -> Int {
    n <= 2 ? 1 : 1 + predicted(n - 1) + predicted(n - 3)
}

for n in [5, 10, 20] {
    calls = 0
    _ = h(n)
    assert(calls == predicted(n))
}
calls = 0; _ = h(30); let c30 = calls
calls = 0; _ = h(31); let c31 = calls
assert(abs(Double(c31) / Double(c30) - 1.4656) < 0.01)

The ratio between consecutive counts approaches the growth rate r, which is one way to find it without solving the equation.

Q3: Merge sort, measured

Using the lesson’s mergeSort, count comparisons for arrays of sizes 2ᵏ, k = 1 to 12, in random order, and check that the count never exceeds N log₂ N. Then check that an already sorted array needs only about half as many.

Show solution
var comparisons = 0

func merge(_ a: ArraySlice<Int>, _ b: ArraySlice<Int>) -> [Int] {
    var result: [Int] = []
    var i = a.startIndex, j = b.startIndex
    while i < a.endIndex && j < b.endIndex {
        comparisons += 1
        if a[i] <= b[j] { result.append(a[i]); i += 1 } else { result.append(b[j]); j += 1 }
    }
    return result + a[i...] + b[j...]
}

func mergeSort(_ values: ArraySlice<Int>) -> [Int] {
    guard values.count > 1 else { return Array(values) }
    let middle = values.startIndex + values.count / 2
    return merge(mergeSort(values[..<middle])[...], mergeSort(values[middle...])[...])
}

for k in 1...12 {
    let n = 1 << k
    comparisons = 0
    let shuffled = Array(0..<n).shuffled()
    assert(mergeSort(shuffled[...]) == Array(0..<n))
    assert(comparisons <= n * k)
}

comparisons = 0
_ = mergeSort(Array(0..<4096)[...])
assert(comparisons == 4096 * 12 / 2)

On sorted input, every merge takes all of the left half first and stops as soon as it runs out, so each merge of two halves of size m makes exactly m comparisons: half the maximum. The order of growth is still Θ(N log N).

Q4: Where the time goes

A function has the recurrence T(N) = 4T(N/2) + N. Draw its tree: how many nodes are on level k, how much work does each do, and which level dominates? Solve it, and check by counting.

Show solution

Level k has 4ᵏ nodes, each working on N/2ᵏ items, so level k does 4ᵏ · N/2ᵏ = 2ᵏ N work. The work doubles on every level down, so the bottom level, with k = log₂ N, dominates: 2^(log₂ N) · N = N². So T(N) is Θ(N²).

var work = 0
func t(_ n: Int) {
    work += n
    if n > 1 {
        for _ in 0..<4 { t(n / 2) }
    }
}

for n in [64, 256, 1024] {
    work = 0
    t(n)
    assert(work == 2 * n * n - n)
}

The exact total, 2N² − N, is a geometric sum of the levels, N + 2N + 4N + … + N². Whether the top, the bottom, or every level equally dominates is what decides the answer, which is the idea behind the “master theorem” that algorithms courses teach next.

Q5 (optional): Fast Fibonacci

The n-th Fibonacci number can be computed with Θ(log n) multiplications: the matrix [[1, 1], [1, 0]] raised to the n-th power contains it, and powers can be computed by squaring, as in Lesson 18. Write it, and write the recurrence for the number of matrix multiplications.

Show solution
typealias Matrix = (Int, Int, Int, Int)   // [[a, b], [c, d]]

var multiplications = 0

func multiply(_ x: Matrix, _ y: Matrix) -> Matrix {
    multiplications += 1
    return (x.0 * y.0 + x.1 * y.2, x.0 * y.1 + x.1 * y.3,
            x.2 * y.0 + x.3 * y.2, x.2 * y.1 + x.3 * y.3)
}

func power(_ m: Matrix, _ n: Int) -> Matrix {
    if n == 1 { return m }
    let half = power(m, n / 2)
    let squared = multiply(half, half)
    return n % 2 == 0 ? squared : multiply(squared, m)
}

func fib(_ n: Int) -> Int {
    n == 0 ? 0 : power((1, 1, 1, 0), n).1
}

assert((0...10).map(fib) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
multiplications = 0
assert(fib(90) == 2_880_067_194_370_816_120)
assert(multiplications <= 2 * 7)

M(n) = M(n/2) + 1 or + 2, so the number of multiplications is at most 2 log₂ n: 90 needs 9 here, where the loop in Lesson 3 needed 90 additions. (The numbers themselves grow, so for huge n each multiplication gets slower; the analysis counts operations on fixed-size integers.)

What’s next

Some operations, like adding to Lesson 30’s array list, are usually instant and occasionally slow. Next lesson: amortized analysis, which gives them a fair cost, and the limits of what big O can tell you.