Scroll to turn the page
Data Structures and Algorithms · Data Structures and Algorithms
counting steps, and how they grow
An algorithm is a finite sequence of precise steps that solves a problem. Two algorithms can solve the same problem at very different costs, and analysis predicts that cost before any code runs.
The figure searches the same sorted list of 15 numbers for 72 twice. Linear search (top) checks one element at a time from the front and needs 11 comparisons. Binary search (bottom) checks the middle of what is left and throws away the half that cannot hold the target: 4 comparisons.
The gap widens as the list grows. In the worst case linear search needs n comparisons and binary search ⌊log₂ n⌋ + 1:
| n | linear | binary |
|---|---|---|
| 15 | 15 | 4 |
| 1,000 | 1,000 | 10 |
| 106 | 1,000,000 | 20 |
| 109 | 1,000,000,000 | 30 |
This chapter is the language for that comparison: counting steps (1.1), growth rates (1.2), Big-O, Ω and Θ (1.3), best, worst and average cases (1.4), recurrences for recursive algorithms (1.5–1.6), and amortized cost (1.7). The code throughout is Python.
the cost model, and T(n)
To analyze an algorithm, count its basic steps (an arithmetic operation, a comparison, an assignment, an index into a list) as a function of the input size n. Each basic step is taken to cost the same constant time. That function is the running time, T(n).
def count_pairs(a): n = len(a) count = 0 for i in range(n): for j in range(i + 1, n): count += 1 # the step counted return count The inner loop runs n − 1 times when i = 0, n − 2 times when i = 1, and so on down to 0, so the counted step runs
(n − 1) + (n − 2) + … + 1 + 0 = n(n − 1)/2
times. For the 6 elements in the figure that is 15: one tile for every pair (i, j) with i < j, filling a triangle that is half of an n × n square.
The exact count depends on what counts as a step, but every reasonable choice gives n²/2 plus terms that grow more slowly. The shape of the growth, quadratic here, is what survives every choice of step and every machine. A loop that runs n times with constant work inside is linear; two nested loops over n are quadratic; a loop that halves its range each time runs about log₂ n times.
log n, n, n log n, n², 2ⁿ
For large inputs, the term that grows fastest decides the running time. The common growth rates, slowest first: constant 1, logarithmic log n, linear n, linearithmic n log n, quadratic n², cubic n³, exponential 2ⁿ and factorial n!.
On the figure n sweeps from 1 to 20. At n = 20, log₂ n is 4.3, n log₂ n is 86, n² is 400, and 2ⁿ has long since left the paper: it is 1,048,576.
At a billion steps a second, the time each needs:
| growth | n = 10 | n = 1,000 | n = 106 |
|---|---|---|---|
| O(log n) | 3.3 ns | 10 ns | 20 ns |
| O(n) | 10 ns | 1 µs | 1 ms |
| O(n log n) | 33 ns | 10 µs | 20 ms |
| O(n²) | 100 ns | 1 ms | 17 minutes |
| O(2ⁿ) | 1 µs | longer than the age of the universe | longer than the age of the universe |
A faster computer multiplies every row by the same constant. It cannot move an algorithm into a better row; only a better algorithm can. That is why analysis drops constant factors and keeps the growth rate.
bounds that hold from some n₀ on
Asymptotic notation states a growth rate while ignoring constant factors and small inputs.
f(n) is O(g(n)) (an upper bound) if there are positive constants c and n₀ with f(n) ≤ c·g(n) for every n ≥ n₀.
f(n) is Ω(g(n)) (a lower bound) if there are positive constants c and n₀ with f(n) ≥ c·g(n) for every n ≥ n₀.
f(n) is Θ(g(n)) (a tight bound) if it is both O(g(n)) and Ω(g(n)).
The figure proves f(n) = 3n² + 5n + 2 is Θ(n²). Upper: take c = 4. 4n² ≥ 3n² + 5n + 2 means n² − 5n − 2 ≥ 0, true from n = 6 on (at n = 5, f is 102 and 4n² only 100; at n = 6, f is 140 and 4n² is 144). Lower: take c = 3: 3n² + 5n + 2 ≥ 3n² for every n ≥ 1.
The same steps show any polynomial of degree d is Θ(nd). Rules that follow from the definitions: constant factors drop (5n² is Θ(n²)); in a sum the fastest-growing term wins (n² + n log n is Θ(n²)); the base of a logarithm does not matter (log₂ n and log₁₀ n differ by the constant factor log₂ 10).
Big-O is only an upper bound: n is also O(n²), true but loose. When the bound is tight, Θ says so.
the same input size, different inputs
Inputs of the same size can cost different amounts. The worst case is the most steps over all inputs of size n, the best case the fewest, and the average case the expected number over some assumed distribution of inputs.
def linear_search(a, target): for i in range(len(a)): if a[i] == target: return i return -1
Linear search on the figure’s 6 values: searching for 7, the first element, takes 1 comparison (best case, Θ(1)). Searching for 4, the last, takes 6, and for 5, which is absent, also 6 (worst case, Θ(n)).
If the target is present and equally likely to be at each of the n positions, the expected number of comparisons is (1 + 2 + … + n)/n = (n + 1)/2: 3.5 here. The average case is Θ(n), only half the worst.
The worst case is the usual guarantee: it bounds every input, needs no assumption about which inputs arrive, and for many algorithms it is also the common case.
the cost of a recursive algorithm
A recursive algorithm’s running time is a recurrence: T(n) defined in terms of T on smaller inputs.
def merge_sort(a): if len(a) <= 1: return a mid = len(a) // 2 left = merge_sort(a[:mid]) right = merge_sort(a[mid:]) return merge(left, right) # n steps
Merge sort makes two recursive calls on halves and merges in about n steps, so
T(n) = 2T(n/2) + n, T(1) = 1
The recursion tree draws every call as a node holding its input size. Level 0 is one call on 8; level 1 two calls on 4; level ℓ has 2ℓ calls on n/2ℓ. Every level therefore does 2ℓ · n/2ℓ = n work, and halving reaches size 1 after log₂ n levels, so there are log₂ n + 1 levels.
For n = 8: 4 levels × 8 = 32, which matches T(8) computed from the recurrence. In general T(n) = n(log₂ n + 1), which is Θ(n log n).
A guess read off a tree can be proved by induction (the substitution method): assume the bound for smaller inputs, and show the recurrence keeps it.
T(n) = aT(n/b) + f(n)
Many divide-and-conquer algorithms split a problem into a subproblems of size n/b and do Θ(nd) work to split and combine. The master theorem solves that recurrence by asking where the work in the recursion tree is.
Level ℓ has aℓ subproblems of size n/bℓ, so it does aℓ(n/bℓ)d = nd(a/bd)ℓ work: a geometric series with ratio a/bd.
| case | work per level | T(n) |
|---|---|---|
| a < bd | shrinks: the root dominates | Θ(nd) |
| a = bd | equal on every level | Θ(nd log n) |
| a > bd | grows: the leaves dominate | Θ(nlog_b a) |
The figure draws the work on each level for n = 8, each recurrence to its own scale: T(n) = 4T(n/2) + n does 8, 16, 32, 64; T(n) = 2T(n/2) + n does 8, 8, 8, 8; T(n) = 2T(n/2) + n² does 64, 32, 16, 8.
Binary search, T(n) = T(n/2) + 1, has a = 1 = 2⁰: Θ(log n). Karatsuba multiplication, T(n) = 3T(n/2) + n, has 3 > 2: Θ(nlog₂ 3) ≈ Θ(n1.585).
The theorem needs subproblems of equal size. T(n) = T(n − 1) + n (insertion sort’s worst case) shrinks by subtraction, not division: unrolling it gives n + (n − 1) + … + 1 = Θ(n²).
the average cost over a sequence
Some operations are usually cheap and occasionally expensive. Amortized analysis bounds the total cost of any sequence of n operations, and divides by n. Unlike the average case, it assumes nothing about the inputs: it is a worst-case guarantee for the whole sequence.
def append(self, x): if self.size == self.capacity: self.capacity *= 2 new = [None] * self.capacity for i in range(self.size): new[i] = self.data[i] # copy self.data = new self.data[self.size] = x self.size += 1
A dynamic array (Python’s list, Java’s ArrayList) keeps its elements in a fixed-size block. When the block is full, append allocates one twice as large and copies everything across. That one append costs Θ(n).
The figure appends 1 to 9 starting at capacity 1. Resizes copy 1 + 2 + 4 + 8 = 15 elements; with the 9 writes, the total cost is 24, about 2.7 per append.
Aggregate method: over n appends the copies are 1 + 2 + 4 + … + 2ᵏ with 2ᵏ < n, which totals less than 2n. Adding the n writes, the total is under 3n, so each append is O(1) amortized.
Growing by a constant amount instead (say 10 slots at a time) copies about n²/20 elements over n appends: Θ(n) amortized. The doubling is what makes it constant.