Professional Documents
Culture Documents
Chapter 9
Recursion
Cumsum(5)=5 + Cumsum(4)
=5 + 4 + Cumsum(3)
=5 + 4 + 3 + Cumsum(2)
=5 + 4 + 3 + 2 + Cumsum(1)
Factorial(5)=5 × Factorial(4)
=5 × 4 × Factorial(3)
=5 × 4 × 3 × Factorial(2)
=5 × 4 × 3 × 2 × Factorial(1)
Fibonacci(5)=Fibonacci(4) + Fibonacci(3)
=Fibonacci(3) + Fibonacci(2) + Fibonacci(2) + Fibonacci(1)
=Fibonacci(2) + Fibonacci(1) + 2 Fibonacci(2) + Fibonacci(1)
=3 Fibonacci(2) + 2 Fibonacci(1)
=3 (Fibonacci(1) + Fibonacci(0)) + 2 Fibonacci(1)
= 5 Fibonacci(1) + 3 Fibonacci(0)
=5
Department of Electronics And Electrical Engineering, IIT Guwahati
Recursion: Binary Search
Base Case: BS(a) = x
Recursion:
BS(a,i,j,x):
mid=(i+j)//2
if a[mid]==x:
𝑛
return mid 𝑇 + 𝑐, 𝑛 > 1
𝑇 𝑛 =ቐ 2
else: 1, 𝑛 = 1
if a[mid]<x:
return BS(a,i,mid-1,x)
else:
return BS(a,mid+1,j,x)
Department of Electronics And Electrical Engineering, IIT Guwahati
Stack Overflow Error in Recursion
Recursion is implemented using stack as activation records are to be stored in LIFO order
If the base
case is
fun1
fun
fun2
Direct Indirect
Substitution Method
Master Method
Department of Electronics And Electrical Engineering, IIT Guwahati
Substitution Method
𝑛
𝑇 + 𝑐, 𝑛 > 1
𝑇 𝑛 =ቐ 2
Form the recurrence relation 1, 𝑛 = 1
𝑛
𝑇 𝑛 =𝑇 +𝑐
2
𝑛
=𝑇 +𝑐+𝑐
Use back substitution to reach 4
𝑛
the base case = 𝑇 2 + 2𝑐
2
𝑛
= 𝑇 3 + 3𝑐
2
⋮
Advantage: 𝑛
Solve any kind of recurrence relation =𝑇 𝑘
+ 𝑘𝑐
2
𝑘
2 =𝑛
Disadvantage:
𝑇 𝑛 = 𝑇 1 + 𝑐 log 2 𝑛 𝑂(log 2 𝑛)
Sometimes complex derivation
𝑇 𝑛 = 1 + 𝑐 log 2 𝑛
𝑇 𝑛 = 𝑛3 . 1 = 𝑂(𝑛3 )