No formulas, no notation — just counting. One loop, two loops, a loop inside a loop. Count the innermost line on small inputs, spot the pattern, and you can compare any two algorithms the exam throws at you.
No reading — this page is the reading. Runestone doesn’t cover Unit 4 (search, efficiency, limits, simulation), so everything you need is right here.
Programs, Algorithms region — Week 2. Last week you counted the steps of two specific algorithms. This week the counting works on any code, and then runs into the edge of what computers can do at all.
Which would you rather run? You don’t need a formula to answer that — you need to be able to count.
Count how many times the innermost line runs. Three shapes cover almost everything on the exam:
| Shape | Innermost line runs | n = 3 | n = 4 | n = 5 | Described as |
|---|---|---|---|---|---|
| One loop over the list | n | 3 | 4 | 5 | linear growth |
| Two loops, one after the other | n + n | 6 | 8 | 10 | still linear |
| A loop inside a loop | n × n | 9 | 16 | 25 | quadratic growth |
count = 0 for a in nums: for b in nums: count = count + 1 # innermost print(count)
count ← 0 FOR EACH a IN nums { FOR EACH b IN nums { count ← count + 1 } } DISPLAY(count)
For every one of the n values of a, the inner loop runs all n values of
b. n groups of n: n × n. With 5 items, 25. With 10 items, 100.
Each square is one run of the innermost line. Pick a shape, then grow n.
Three procedures, three growth rates. Predict before you code — your predictions are graded for existing, not for being right. Then instrument each one with a counter and fill in the growth table for n = 3, 5, and 10.
Five questions. For each one, find the innermost line first, then count.
Suppose a social network wanted to suggest friends by comparing every user to every other user. With 3 billion users, that’s a loop inside a loop: about 9 × 1018 comparisons. At a billion comparisons a second, one pass takes roughly 285 years.
So nobody builds it that way. Engineers throw out quadratic designs at that scale and find cleverer ones — or drop the feature. Efficiency quietly decides which features exist at all.