CS341_Recursion (1)
CS341_Recursion (1)
fibonacci(3) fibonacci(2)
fibonacci(3) fibonacci(2)
fibonacci(2) fibonacci(1)
fibonacci(3) fibonacci(2)
+
fibonacci(2)->1 fibonacci(1)->0
fibonacci(3)->1 fibonacci(2)->1
return result;
}
22 18 12 -4 58 7 31 42
split split
22 18 12 -4 58 7 31 42
split split split split
22 18 12 -4 58 7 31 42
merge merge merge merge
18 22 -4 12 7 58 31 42
merge merge
-4 12 18 22 7 31 42 58
merge
-4 7 12 18 22 31 42 58
11/4/2024 CS341: Recursion 30
Merging sorted halves
11/4/2024 CS341: 38
Recursion
Big ‘O’ of Recursion
1. Recurrence Relations:
1. Define a recurrence relation that represents the time complexity in terms of the input size.
2. Solve the recurrence relation to obtain a closed-form expression for the time complexity.
3. Common techniques for solving recurrence relations include substitution, recursion trees, and the
master theorem.
2. Recursion Trees:
1. Create a recursion tree that visualizes the recursive calls made by the algorithm.
2. Analyze the depth of the tree (number of recursive levels) and the number of nodes at each level.
3. Sum the work done at each level of the tree to determine the overall time complexity.
3. Master Theorem:
1. The master theorem is a specific method for analyzing the time complexity of divide-and-conquer
recursive algorithms.
2. It provides a general framework for identifying the time complexity in terms of big O notation based
on the structure of the recurrence relation.
11/4/2024 CS341: 39
Recursion
Solving Recurrence Relations - Iteration method
• Steps:
▪ Expand the recurrence
▪ Express the expansion as a summation by plugging the
recurrence back into itself until you see a pattern.
▪ Evaluate the summation
• In evaluating the summation one or more of the
following summation formulae may be used:
• Arithmetic series:
• Special Cases of Geometric Series:
• Geometric Series:
11/4/2024 CS341: Recursion 40
Solving Recurrence Relations - Iteration method
• Harmonic Series:
• Others:
public static void hanoi(int n, char from, char to, char temp){
if (n == 1)
System.out.println(from + " --------> " + to);
else{
hanoi(n - 1, from, temp, to);
System.out.println(from + " --------> " + to);
hanoi(n - 1, temp, to, from);
}
}
11/4/2024 CS341: 49
Recursion
Quicksort A[p…q] ≤ A[q+1…r]
• Conquer
• Recursively sort A[p..q] and A[q+1..r] using Quicksort
• Combine
• Trivial: the arrays are sorted in place
• No additional work is required to combine them
• The entire array is now sorted
11/4/2024 CS341: 50
Recursion
Partition Implementation (Java)
static int Partition(int[] a, int left, int
right) {
int p = a[left], l = left + 1, r = right;
while (l < r) {
while (l < right && a[l] < p) l++;
while (r > left && a[r] >= p) r--;
if (l < r) {
int temp = a[l]; a[l] = a[r]; a[r]
= temp;
}
}
a[left] = a[r];
a[r] = p;
return r;
}