Lec - 4 Recursion I
Lec - 4 Recursion I
return Fact(n-1)*n
Fact(3)
if (3 == 0 )
return 1;
else
return Fact(3-1)*n
Fact(2)
if (2 == 0 )
return 1;
else
return Fact(2-1)*n
Fact(1)
if (1 == 0 )
return 1;
else
return Fact(1-1)*n
Fact(0)
if (0 == 0 )
return 1;
else
return Fact(0-1)*0
Fact(3)
if (3 == 0 )
return 1; 6
else 6
return Fact(3-1)*3
Fact(2)
if (2 == 0 )
return 1;
else 2
return Fact(2-1)*2
Fact(1)
if (1 == 0 )
return 1;
else 1
return Fact(1-1)*1
Fact(0)
if (0 == 0 )
return 1;
else
return Fact(0-1)*0
T(n) = time of recursive base + time of base case
Fact(n)
if (n == 0 )
1
T(n)=T(n-1)+1
return 1;
else
return Fact(n-1) T(n-1)
Fact(n)
if (n == 0 )
1
return 1;
else
return 2*Fact(n-1) T(n-1)
T(n)=1+2T(n-1) or T(n)=1+T(n-1)
Fact(n)
if (n == 0 )
1
return 1;
else
return Fact(n/2) T(n/2)
T(n)=1+T(n/2)
Fact(n)
if (n == 0 )
1
return 1;
else
return Fact(n/2)+ Fact(n/2) T(n/2) + T(n/2)
T(n)=T(n/2) +T(n/2)+1
T(n)=2T(n/2)+1
Fact(n)
if (n == 10 )
for i=1 to n 𝑛
1
print i 𝑖=1
return 1;
else
return Fact(n-1)+ Fact(n-2) T(n-1) + T(n-2)
𝑛
T(n)=T(n-1) +T(n-2)+ 𝑖=1 1
T(n)=T(n-1) +T(n-2)+n
𝑇(𝑛) = 2𝑇(𝑛/2) + 𝑛
𝑛
𝑂(𝑛) 𝑇 𝑛 =𝑇 +1
4
𝑇(𝑛) = 𝑇(𝑛 − 1) + 𝑐
An equation or inequality that describes a function in terms of its
value on smaller inputs.
T(n) = T(n-1) + n
Tree method
Master method
Convert the recurrence into a tree:
– Each node represents the cost incurred at various
levels of recursion
T(n) = 2T(n/2) + n
T(n/2) T(n/2)
n/2 n/2
Num of children child Parent (root)
height
by number of rules:
If the recursion part in equation T(n/4) T(n/4) T(n/4) T(n/4)
contain division,T(n) = 2T(n/2) + n n/4 n/4 n/4
n/4
…
height = 𝐥𝐨𝐠 𝒃 𝒏
T(n/8) T(n/8) T(n/8) T(n/8)
If the recursion part in equation
contain subtraction,T(n) = 2T(n-1) + n
height = 𝒏
Tree method
L_0 n
1. Summation L_1 = n
L_2 = n
If all values of levels are equal
log2 𝑛
ℎ𝑒𝑖𝑔ℎ𝑡
𝑇 𝑛 = 𝑛
𝑇 𝑛 = 𝑙𝑒𝑣𝑒𝑙 𝑣𝑎𝑙𝑢𝑒 𝑖=1
𝑖=1
𝑇 𝑛 = 𝑛 . log 2 𝑛
This equation doesn’t contain recursion
# Ο(𝑛 . log 𝑛)
Tree method
Tree=1+3+5+7+…
2. Arithmetic
If the difference between 𝐿1 = 𝑣𝑎𝑙𝑢𝑒 𝑜𝑓 𝑙𝑒𝑣𝑒𝑙 1
𝐿𝑛 = 𝑣𝑎𝑙𝑢𝑒 𝑜𝑓 𝑙𝑎𝑠𝑡 𝑙𝑒𝑣𝑒𝑙
levels values is a sum or
h = ℎ𝑒𝑖𝑔ℎ𝑡
subtraction
𝐿1 + 𝐿𝑛
𝑇 𝑛 = ℎ( )
2
Tree method
Multiplication
3. Geometric Tree=1+2+4+8+…
If the difference between
levels values is a multiplied or 𝐿1 = 𝑣𝑎𝑙𝑢𝑒 𝑜𝑓 𝑙𝑒𝑣𝑒𝑙 1
𝑟 = 𝑚𝑢𝑡𝑖𝑝𝑙𝑖𝑒𝑑 𝑣𝑎𝑙𝑢𝑒
divided h = ℎ𝑒𝑖𝑔ℎ𝑡
Division
1 − 𝑟ℎ
1 1
𝑇𝑟𝑒𝑒 = + + +…
1 𝑇 𝑛 = 𝐿1 ( )
2 4 8 1−𝑟
𝐿1 = 𝑣𝑎𝑙𝑢𝑒 𝑜𝑓 𝑙𝑒𝑣𝑒𝑙 1
𝑟 = 𝑚𝑢𝑡𝑖𝑝𝑙𝑖𝑒𝑑 𝑣𝑎𝑙𝑢𝑒
𝐿1
𝑇 𝑛 =
1−𝑟