Reading recurrences: T(n) = 2T(n/2) + n
Divide and conquer cost = (number of calls) × (work per call), level by level. : log n levels × n work = .
The idea
A algorithm's cost is a : T(n) = a·T(n/b) + f(n) means a subcalls on inputs of size n/b plus f(n) work to split and combine.
Draw the call tree. Merge sort has log₂ n levels, and each level does n total work, so n log n. is T(n) = T(n/2) + 1: log n levels of . Naive , T(n) = T(n−1) + T(n−2) + 1, doubles each level: about 2ⁿ.
Worked example
Three common recurrences
- T(n) = T(n/2) + O(1) → : binary search.
- T(n) = 2T(n/2) + → O(n log n): merge sort.
- T(n) = 2T(n/2) + O(1) → O(n): visiting every of a tree.
Pseudocode
The steps in plain words. ← means “set to”; indentation shows what's inside what.
See it run
The worked example, step by step, beside the Python. The highlighted line is the one running.
Step-by-step
T(n) = 2T(n/2) + n, n = 8
level 0: call sizes
Solution · Pythonline 5
def merge_sort(nums): # T(n) = 2T(n/2) + nif len(nums) <= 1:return numsmid = len(nums) // 2left, right = merge_sort(nums[:mid]), merge_sort(nums[mid:])merged, i, j = [], 0, 0while i < len(left) and j < len(right):if left[i] <= right[j]:merged.append(left[i]); i += 1else:merged.append(right[j]); j += 1return merged + left[i:] + right[j:]Step 1 of 6· line 5
T(n) = 2T(n/2) + n reads: two calls on halves, plus n work to merge. Draw it as a tree of calls and add up each level.
Merge sort: O(n log n) time, O(n) space.
How to spot it
- Any recursion that splits the input: sorting, tree , , “divide in half”.
Common mistakes
- Counting only one level's work.
- Assuming every split is even: 's is T(n) = T(n−1) + n = .
Where it comes up
Go further
Up next for you · Beginner
“Have I seen this?” is a set →