Design and Analysis of Algorithms: Recursion
Design and Analysis of Algorithms: Recursion
ALGORITHMS
Lecture 7
Recursion
Recursive Definition
To define objects/processes in terms of simpler
objects/processes
In simple words converting a problem into similar
2
Recurrence Relation
To analyse a recursive problem we need to write
recurrence relation.
A formula which represent a bigger problem into
smaller problem.
1 2 3 …… n
Total work= Fill all places with general sequence.
How to fill first position? Either: 0|1
0
n-1
1 2 3 …… n
1
n-1
1 2 3 …… n
Problem 1:
How many binary sequences possible of size n?
So far,
T(n)=T(n-1)+T(n-1)
T(n)=2T(n-1)
T(n)=2T(n-1) , n>1
T(1)=2 recurrence relation
A(){ T (n) 1 T (n 1) 1
if(n>1)
return(A(n-1)) T (n 1) 1 T (n 2) 2
} T (n 2) 1 T (n 3) 3
O(n2)
Recurrence (Master Theorem)
Recurrence (Master Theorem)
T (n) aT ( ) (n log n)
n k p
b
where a 1, b 1, k 0 and p is real number
1) if a b , then T (n) (n
k logba
)
2) if a b
k
T (n) 3T ( n ) n2
2
a 3, b 2, k 2 and p 0
Compare a with bk
a bk
3 22
So
3 4
a < bk
Because a<bk , condition 3 of Master theorem is true
T (n) 4T ( n ) n2
2
a 4, b 2, k 2 and p 0
Compare a with bk
a bk
4 22
So
4 4
a = bk
Because a=bk , condition 2 of Master theorem is true
T ( n) T ( n ) n 2
2
a 1, b 2, k 2 and p 0
Compare a with bk
a bk
1 22
So
1 4
a < bk
Because a<bk , condition 3 of Master theorem is true
T (n) 2T ( n ) n log n
2
a 2, b 2, k 1 and p 1
Compare a with bk
a bk
2 21
So
2 2
a = bk
Because a=bk , condition 2 of Master theorem is true