Module 1-Lecture4
Module 1-Lecture4
EVEN 2022
Module 1: Lecture 4
Recursion Tree - A visual representation of recursive call hierarchy where each node
represents the cost of a single subproblem
2
T(n) = 2T(n/2) + c
3
T(n) = 2T(n/2) + cn
• To find no. of levels: Consider the longest path from root to leaf
• (9/10)0n –> (9/10)1n –> (9/10)2n –> ……… –> (9/10)in
• Size of problem at last level = 1 = (9/10)i
• i = log10/9(n)
• No. of levels = 1+ log10/9(n)
• No. of nodes at level 0 = 20 = 1
• No. of nodes at level 1 = 21 = 2
• …
• No. of nodes at level log2(n) = 2^log10/9(n) = n^log10/9(2)
• Cost of sub problems at last level = n^log10/9(2)
T(n) = n + n + n + —- (no. of levels-1) times + last level cost
= n + n + n + —- log10/9(n) times + Θ(n^log10/9(2))
= cnlog10/9(n) + Θ(n^log10/9(2))
• T(n) = Θ(nlog10/9n)
Master Theorem
• General formula that works if recurrence has the form T(n) = aT(n/b) + f(n)
• a is number of sub-problems
• n/b is size of each sub-problem
• f(n) is cost of non-recursive part
7
Master Theorem
8
Case-1
9
10
The master theorem cannot be used if:
11
Examples on Masters Theorem
13
• Recurrence relation for mater’s method can also be represented as
Where, a >= 1, b > 1, k >= 0 and p is a real number
Case-01: Case-03:
• If a > bk, then T(n) = θ (nlogba) • If a < bk and
Case-02: • If p < 0, then T(n) = O (nk)
• If a = bk and • If p >= 0, then T(n) = θ (nklogpn)
• If p < -1, then T(n) = θ (nlogba)
• If p = -1, then T(n) = θ (nlogba.log2n)
• If p > -1, then T(n) = θ (nlogba.logp+1n)
14
T(n) = 3T(n/2) + n2 T(n) = 2T(n/2) + nlogn
• a = 3, b = 2, k = 2, p = 0 • a = 2, b = 2, k = 1, p = 1
• Now, a = 3 and bk = 22 = 4. • Now, a = 2 and bk = 21 = 2.
• Clearly, a < bk. • Clearly, a = bk.
• So, we follow case-03. • So, we follow case-02.
• Since p = 0, so we have- • Since p = 1, so we have-
• T(n) = θ (nklogpn) = θ (n2log0n) = θ (n2) • T(n) = θ (nlogba.logp+1n) = θ (nlog22.log1+1n)
= θ (nlog2n)
15
T(n) = √2T(n/2) + logn T(n) = 8T(n/4) – n2logn
• a = √2, b = 2, k = 0, p = 1 • The given recurrence relation does not
• Now, a = √2 = 1.414 and bk = 20 = 1. correspond to the general form of Master’s
theorem.
• Clearly, a > bk.
• So, it can not be solved using Master’s
• So, we follow case-01. theorem.
• So, we have-
• T(n) = θ (nlogba) = θ (nlog2√2) = θ (n1/2)
16
T(n) = T(√n) + 1
• We can not directly apply Master’s Theorem on this recurrence relation.
• However, we can modify and bring it in the general form to apply Master’s theorem.
• Let n = 2m T(2m) = T(2m/2) + 1
• Now, let T(2m) = S(m), then T(2m/2) = S(m/2)
• So we have: S(m) = S(m/2) +1 (Now, we can easily apply Master’s Theorem)
• We compare the given recurrence relation with S(m) = aS(m/b) + θ (mklogpm).
• a = 1, b = 2, k = 0, p = 0
• Now, a = 1 and bk = 20 = 1 and Clearly, a = bk.
• So, we follow case-02.
• Since p = 0, so we have-
• S(m) = θ (mlogba.logp+1m) = θ (mlog21.log0+1m) = θ (logm)
• T(n) = θ (loglog2n)
17