Professional Documents
Culture Documents
05 Recursion - in Class Ex Solution
05 Recursion - in Class Ex Solution
16
8 8
4 4 4 4
2 2 2 2 2 2 2 2
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
power2(3, 16)
No of instances No of multiplications
Note that there are 2 multiplications if n is odd, 1 multiplication if n is even, and 0 multiplication for n == 0.
Note that there are 2 recursive calls for any n > 0, and zero recursive call for n == 0.
Complexity of power2
0 1 2 3 4 5
26 34 64 83 2 5
0 1 2 3 4 5
26 34 64 83 2 5
0 1 2 3 4 5
26 34 64 83 2 5
0 1 2 3 4 5
input 26 34 64 83 2 5
Merge sort: Top-down Approach
0 1 2 3 4 5
input 26 34 64 83 2 5
divide
0 1 2 3 4 5
26 34 64 83 2 5
0 1 2 3 4 5
26 34 64 2 5 83
conquer
0 1 2 3 4 5
output 2 5 26 34 64 83
Merge sort: Bottom-up Approach
0 1 2 3 4 5 6 7 8
4 12 30 52 59 64 67 79 98
0 1 2 3 4 5 6 7
4 12 30 52 59 64 67 98
0 1 2 3 4 5 6 7 8
30 52 59 98 4 12 64 67 79
0 1 2 3 4 5 6 7 8
30 52 59 98 4 67 12 64 79
0 1 2 3 4 5 6 7 8
52 30 98 59 67 4 64 12 79
Merge sort: Top-down Approach
0 1 2 3 4 5 6 7 8
input 52 30 98 59 67 4 64 12 79
divide
0 1 2 3 4 5 6 7 8
52 30 98 59 67 4 64 12 79
0 1 2 3 4 5 6 7 8
30 52 59 98 4 12 64 67 79
conquer
0 1 2 3 4 5 6 7 8
output 4 12 30 52 59 64 67 79 98