Unit #3 Divide and Conquer Algorithm: Tejas Chauhan
Unit #3 Divide and Conquer Algorithm: Tejas Chauhan
Tejas Chauhan
Divide and Conquer
› Recursive in structure
› Divide the problem into sub-problems that are
similar to the original but smaller in size
cn/2 cn/2
T(n/2) T(n/2)
T(n/4) T(n/4) T(n/4) T(n/4)
Cost of sorting
subproblems.
Thursday, March 21, 2024 Tejas Chauhan 11
Recursion Tree for Merge Sort
Continue expanding until the problem size reduces to 1.
cn cn
cn/2 cn/2 cn
log n
cn/4 cn/4 cn/4 cn/4 cn
c c c c c c cn
Total : cn logn+cn
Thursday, March 21, 2024 Tejas Chauhan 12
Recursion Tree for Merge Sort
Continue expanding until the problem size reduces to 1.
cn
There are log n+1 levels,
height is log n.
c c c c c c
Thursday, March 21, 2024 Tejas Chauhan 13
Recursion Trees – Caution Note
› Recursion trees only generate guesses.
› Verify guesses using substitution method.
n
2 n2
5 2
(n/4)2
T(n/4) T(n/2)
(n/2) 2 n
16
25 2
(n/16)2
T(n/16) (n/8)2
T(n/8) (n/8)
T(n/8)2
T(n/4)
(n/4)2 n
256
…
…
2 5 5
2
5
3
Total = n 1 ...
Q(1) 16 16 16
= Q(n2)
Thursday, March 21, 2024 Tejas Chauhan 15
The Master Method
› The master method applies to recurrences of
the form
T(n) = a T(n/b) + f (n) ,
› where a ≥ 1, b > 1, and f is asymptotically
positive.
…
…
…
…
…
…
…
…
› p = wy = 09 x 12 = 108
› q = xz = 81 x 34 = 2754
› r = (w + x) x (y + z) = 90 x 46 = 4140
0981 x 1234
09 x 12 81 x 34 90 x 46
P1 = Multiply(xL, yL)
P2 = Multiply(xR, yR)
P3 = Multiply(xL+xR, yL+yR)
return P1x2n + (P3-P1-P2)x2n/2 + P2
› T(n) = O(n3)
0
X =
1
X Y XY
A B E F AE BG AF BH
XY
C D G H CE DG CF DH
P5 P4 P2 P6 P1 P2
XY
P3 P4 P1 P5 P3 P7
Function expoSeq(a, n) {
ra
for i 1 to n-1 do r a*r
return r
}
› T(n) = O(n)
Thursday, March 21, 2024 Tejas Chauhan 39
Exponentiation
› With divide and conquer:
› an = return a if n = 1
2
return (a )
n/2
if n is even
return a * an-1 otherwise
›
2
a = a * a = a * (a ) …….
29 28 14
Function expoDC(a, n) {
if n = 1 then return a
if n is even then return [expoDC(a, n/2)]2
return a * expoDC(a, n - 1)
}
› T(n) = O(log n)