Recurrence Relations
Recurrence
For a recursive algorithm, we cannot directly calculate time complexity simply by counting how many times each statement executes. Instead, we can form a recurrence relation and solve it through iterative expansion.
Summation
int sum(int n) {
if (n <= 0) {
return 0;
}
return sum(n - 1) + n;
}KNOWLEDGE QUIZ
T(n) = T(n-1) + 1 and T(0) = 1. How many expansion levels reach the base case?
Insertion sort
void insertion_sort(int arr[], int n) {
if (n <= 1) {
return;
}
insertion_sort(arr, n - 1);
int last = arr[n - 1];
int j = n - 2;
while (j >= 0 && arr[j] > last) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = last;
}KNOWLEDGE QUIZ
T(n) = T(n-1) + n. What sequence of added work appears after expansion?
Tower of Hanoi
There are three towers, A, B, and C. Tower A holds disks stacked from largest at the bottom to smallest at the top. The goal is to move all disks from A to C. Only one disk may move at a time, and a larger disk may never be placed on a smaller one.
A recursive algorithm solves the Tower of Hanoi in three stages:
- Move the first disks from A to B, using C as the helper.
- Move the final, largest disk directly from A to C.
- Move the disks from B to C, using A as the helper.
void hanoi(int n, char A, char B, char C) {
if (n == 1) {
move(1, A, C);
} else {
hanoi(n - 1, A, C, B);
move(n, A, C);
hanoi(n - 1, B, A, C);
}
}Solve the four-disk Tower of Hanoi
Move all four disks from A to C. Click a source tower, then a destination tower. The optimal solution takes 15 moves.
KNOWLEDGE QUIZ
T(n) = 2T(n-1) + 1, what does the coefficient 2 represent?
If each move takes one second, solving a 64-disk Tower of Hanoi would take about 580 billion years.
Expand and solve recurrences
Use iterative expansion on these recurrences. For each one, show at least two expansions, the general kth expansion, the stopping condition, and the final asymptotic complexity.
T(0) = 1,T(n) = T(n-1) + 3.T(0) = 1,T(n) = T(n-1) + n.T(1) = 1,T(n) = 2T(n-1) + 2.