Professional Documents
Culture Documents
UNIT-2
2
Recursion
• The process in which a function calls itself directly or indirectly
is called recursion and the corresponding function is called as
recursive function.
• Examples of such problems are Factorial, Towers of Hanoi
(TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of
Graph, etc.
3
Example
int fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}
4
Recurrence Relation
Recurrence Relation
Recursion Tree
Formulas:
𝑛 𝑖
𝑛 4) 𝑖=0 𝑥 =
1) 𝑖=0 1 = (n+1)
1
𝑛 𝑛(𝑛+1) x<1
2) 𝑖=0 𝑖 = 2 1−𝑥
3) 𝑛
𝑖=0 𝑖
2
=
𝑛(𝑛+1)(2𝑛+1)
x=1 n+1
6
𝑥 𝑛+1 −1
x>1
𝑥−1
8
Ques 1
𝑛
T(n) = 2T ( +17) +n
2
Ans: nlog2n
9
Ques 2
𝑛
T(n) = T ( ) +1
2
Ans: log2n
10
Ques 3
𝑛
T(n) = 2T ( ) +1
2
Ans: n
11
Ques 4
T(n) = T (n-1) +n
Ans: n2
12
Ques 5
𝑛
T(n) = 4T ( ) +n
3
Ans: n1.26
13
Ques 6
𝑛
T(n) = 16T ( ) +n3
4
Ans: n3
14
Ques 6
n1/2=2m/2
Ques 7
𝑛 2𝑛
T(n) = T ( ) + T ( ) + n
3 3
Ques 8
9𝑛
T(n) = T ( ) + n
10
Ans: n
17
Ques 9
𝑛 𝑛 𝑛
T(n) = T ( ) +T ( ) +T ( ) +n
2 4 8
Ans: nlog23
18
2. Master Theorem
If a>= 1and b>1 be constants, let f(n) be a function and T(n) be defined on the
non-negative integers by the recurrence
T(n) = aT(n/b) + f(n)
Ques 1
Case2:
Θ(nlogba log n)
=Θ(nlog n)
22
Ques 2
𝑛
a=4, b=2, f(n)=n
T(n) = 4T ( ) +n
2
Find nlogba
Ans: n2 = nlog24
=n2 =n2-ϵ
Case1:
Θ(nlogba)
=Θ(n2)
23
Ques 3
Ques 4
𝑛
T(n) = 49T ( ) +n
7
Ans: n2
25
Ques 5
𝑛
T(n) = 2T ( ) +logn
2
Master Theorem
27
3. Iteration Method
Example
29
Example
30
Example
31
Example
32
Example
34
Question 1
35
Solution 1
36
Solution 1
37
Solution 1
38
Solution 1
39
Question 2
Θ(lg(n))
40
Question 3
T(n) = 2T(n/2) + n
Θ(nlg(n))
41
4. Substitution Method
• The Substitution Method Consists of two main steps:
1. Guess the Solution.
2. Use the mathematical induction to find the boundary
condition and shows that the guess is correct.
42
Example
Recurrence relation: T(1) = 1 and T(n) = 2T(n/2) + n for n > 1
Step 4: Now we need to put the values into the recurrence formula,
T(2) = 2T(1) + 2 = 4 and T(3) = 2T(1) + 3 = 5,
Now choose a c that perfectly fits our inequality obtained above in step 3, let say c = 2 :
4 ≤ 4log(2) and 5 ≤ 6log(3) perfectly satisfy the condition,
Hence we can conclude that T(n) ≤ 2n log n for all n ≥ 2, therefore T(n) = O(n log n)
43
Question 1
Solve the equation by Substitution Method.
44
Question 2
T(n)=4T(n/2)+n