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.
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)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.
Binary search
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.
}visit(3)calls += 1visit(depth - 1)var calls = 0func visit(_ depth: Int) {print(calls)guard depth > 0 else { return }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)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 NFor 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.