Recurrence Relations and Recursive Algorithm Analysis
Learning Goals
- Goal 1
From Code to Recurrence: The Derivation Process
To analyze a recursive algorithm, you must first convert the code into a mathematical Recurrence Relation. This represents the total time as a sum of the work done at the current level plus the time taken by recursive calls.
1. Linear Recursion (e.g., Factorial)
1int factorial(int n) { 2 if (n == 0) return 1; // Base Case: Constant time c1 3 return n * factorial(n - 1); // Recursive step: T(n-1) + c2 (multiplication) 4}
Recurrence: (where 1 is constant time for comparison/multiplication).
2. Divide and Conquer (e.g., Binary Search)
1int binarySearch(int A[], int low, int high, int x) { 2 int mid = (low + high) / 2; // Constant work: c 3 if (x == A[mid]) return mid; 4 if (x < A[mid]) 5 return binarySearch(A, low, mid-1, x); // T(n/2) 6 else 7 return binarySearch(A, mid+1, high, x); // T(n/2) 8}
Recurrence: . (Note: We only make ONE recursive call, not two).
3. Multiple Subproblems (e.g., Merge Sort)
Merge sort divides the array into two halves, calls itself twice, and then merges them. Recurrence: . (The comes from the linear-time Merge process).
Formal Analysis: The Substitution Method (Induction)
In university exams, you are often asked to "Prove by induction" that a recurrence has a specific bound. This is the formal side of the Substitution Method.
Problem: Prove that is .
Step 1: The Guess We guess that for some constant .
Step 2: Mathematical Induction (The Hypothesis) Assume the guess holds for all values up to . Therefore:
Step 3: Substitution Substitute the hypothesis into the original recurrence:
Step 4: Prove the Bound We need to show that . This is true if . . This holds for and sufficiently large . Conclusion: .
Space Complexity: Tracing the Recursion Stack
- 1Step 1
Every time a recursive function is called, the system allocates a 'Stack Frame' containing local variables, parameters, and the return address. This consumes physical memory.
- 2Step 2
For
factorial(n), the calls go: . There are active frames on the stack at the deepest point. Space Complexity: . - 3Step 3
For Binary Search, the problem size halves at each step: . The number of steps is . Space Complexity: .
- 4Step 4
Merge sort also has a tree depth of . However, it also uses an auxiliary array of size for merging. Total Space Complexity: (dominated by the array).
The Master Theorem Gap
Master's Theorem cannot solve recurrences where is not polynomially smaller/larger than . For example, . Here, . . Since is only 'logarithmically' larger than , not 'polynomially' larger (), the theorem fails. You must use the Recursion Tree method instead.
Knowledge Check
What is the recurrence relation for a recursive algorithm that divides a problem of size n into 3 subproblems of size n/3 and spends O(n) time combining them?