Sub topic 3
Analyzing Recursion and Practical Complexity
Assume you know variables, loops, functions, recursion, arrays, and basic algebra. This chapter focuses on how recursive work grows and how asymptotic results relate to real programs.
Recurrence Relations
A recurrence describes an algorithm's cost in terms of smaller inputs. Merge sort splits an input of size n into two halves, recursively sorts them, and merges the results in linear time:
\[ T(n) = 2T(n/2) + O(n) \]
The 2T(n/2) term represents the two recursive calls. The O(n) term represents merging.
def merge_sort(items):
if len(items) <= 1:
return items
mid = len(items) // 2
left = merge_sort(items[:mid])
right = merge_sort(items[mid:])
result = []
while left and right:
result.append(left.pop(0) if left[0] <= right[0] else right.pop(0))
return result + left + right
print(merge_sort([4, 1, 3, 2]))Solving Recurrences
Unrolling shows the pattern:
- Level 0 does
nmerge work. - Level 1 does
ntotal merge work. - Every level does
nwork. - There are
log₂ nlevels.
Therefore, the total is O(n log n).
The Master Theorem gives the same result for recurrences shaped like:
\[ T(n) = aT(n/b) + f(n) \]
For merge sort, a = 2, b = 2, and f(n) = n. Since n matches n^(log₂2), the result is O(n log n).
Space and the Call Stack
Time complexity counts operations. Space complexity counts extra memory. Merge sort uses O(n) space for merged lists and O(log n) stack space for recursive calls. The larger term usually determines the total: O(n).
Amortized Analysis
Amortized analysis averages a sequence of operations without assuming a probability distribution. A dynamic array sometimes copies all elements when it grows, so one append can cost O(n). However, doubling capacity makes resizing rare. Across many appends, the total copying is O(n), so each append costs O(1) amortized.
Data Structure Costs
| Operation | Array | Hash table | Balanced tree |
|---|---|---|---|
| Lookup by key | O(1) index | O(1) average | O(log n) |
| Search by value | O(n) | O(n) | O(n) |
| Insert | O(n) middle | O(1) average | O(log n) |
When Big O Is Not Enough
Big O ignores constants, cache behavior, allocation costs, and small inputs. An O(n²) algorithm with simple operations can beat an O(n log n) algorithm for a small n. Benchmark representative workloads after proving that the algorithm is correct.
Exercise
What is the time complexity of T(n) = T(n/2) + O(1)?
Show answer
O(log n), because the input is halved at each level and there are logarithmically many levels.