level 0level 1level 2level 3n = 8441def cost(n):2 if n == 1:3 return 14 a = cost(n // 2)5 b = cost(n // 2)6 return a + b + n222211111111abf(n)leavesT(8)
Tree blocks: one call each, as wide as the steps it does itselfTowers: the total of one level of the tree (one slice = 4 steps)A hopping block: a level's total moving to its towerThe recursion tree of cost(8): each block is one call, as wide as the steps it does on its own, so every level adds up to 8 and T(8) = 32. The towers at the back are the level totals. Equal towers mean Θ(n log n); towers growing toward the leaves mean the leaves win; towers shrinking toward the leaves mean the root wins.

Draw the recursion tree

  1. 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.

Add up the levels

The master theorem

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.