Draw the recursion tree
This Python function counts the steps of a divide-and-conquer algorithm. A call on size 1 costs 1 step. A bigger call makes two calls on halves, then does n steps of its own. So T(n) = 2T(n/2) + n, with T(1) = 1.
Call cost(8). Leave its two calls aside for now: on its own, the call does 8 steps, the + n. Draw it as a block 8 units wide. It is the root of a recursion tree, and level 0 costs 8 steps.
The root’s two calls are cost(4) and cost(4). Each does 4 steps of its own, so each child block is half as wide. Level 1 has 2 calls: 2 × 4 = 8 steps, the same as level 0.
Each cost(4) calls cost(2) twice. Level 2 has 4 calls doing 2 steps each: 4 × 2 = 8 again. Going down a level, the number of calls doubles while each call’s own work halves.
Each cost(2) calls cost(1) twice. Now n == 1, so these calls stop and return 1. They are the leaves: 8 × 1 = 8 steps. Halving 8 reaches 1 after 3 splits, because log₂ 8 = 3.
Add up the levels
Add the levels: 4 levels of 8 steps, so T(8) = 32, which is what cost(8) returns. For any power of 2 there are log₂ n + 1 levels of n steps: T(n) = n log₂ n + n = Θ(n log n).
The master theorem
Many recursive algorithms share one shape: T(n) = a·T(n/b) + f(n). A call makes a calls on pieces of size n/b, plus f(n) steps of its own. Our function has a = 2, b = 2 and f(n) = n.
The master theorem compares f(n) with the number of leaves, n^(log_b a). Here that is n¹: 8 leaves, and f(n) = n grows just as fast. Every level costs the same, so T(n) = Θ(n log n).
Make four calls instead: a = 4. Now there are 4³ = 64 leaves, that is n², which grows faster than f(n) = n. Level costs double: 8, 16, 32, 64. The leaves win: T(n) = Θ(n²).
Back to two calls, but now f(n) = n². Level costs halve: 64, 32, 16, 8, so the root’s own work wins: T(n) = Θ(n²). This case also needs a·f(n/b) ≤ c·f(n) for some c < 1; here c = ½.
What happens
;; step 1/10 · the-function the recurrence, read off the code: n == 1 return 1 T(1) = 1 two calls cost(n // 2) × 2 2·T(n/2) own work + n n T(n) = 2T(n/2) + n like merge sort: two halves, then a merge of n items
The rule used here is the simple form from MIT 6.006 for T(n) = a·T(n/b) + Θ(n^c): if c < log_b a the leaves dominate and T(n) = Θ(n^(log_b a)); if c = log_b a every level costs about the same and T(n) = Θ(n^c log n); if c > log_b a the root dominates and T(n) = Θ(n^c). CLRS §4.5 states the full theorem for any f(n). The figure uses n = 8, a power of 2, so every halving is exact and n // 2 equals n/2. For other n the pieces differ by at most 1 and the Θ answers stay the same.