week_4
week_4
Algorithms
Shahid Hussain
Week 4: September 9, 11: Fall 2024
1
Divide and Conquer Algorithms
Master Theorem
Theorem
Let L(n) be a function depending on natural n. Let c be a
natural number, c ≥ 2, a, b, γ be real constants such that,
a ≥ 1, b > 0, γ ≥ 0, and for any n = ck , where k is an arbitrary
natural number, the following inequality holds:
n
L(n) ≤ aL + bnγ .
c
Suppose for any natural k for any n ∈ {ck + 1, ck + 2, . . . , ck+1 }
the inequality L(n) ≤ L(ck+1 ) holds. Then:
γ
O(n ) if γ > logc a,
L(n) = O(nlogc a ) if γ < logc a,
O(nγ log n) if γ = logc a.
2
Proof of Master Theorem
3
Proof of Master Theorem (cont.)
4
Proof of Master Theorem (cont.)
7
Merge Sort
Algorithm: mergesort
Input: A = ⟨a1 , . . . , an ⟩: a sequence of n numbers
Output: A sorted permutation of A
1. if n > 1 then
2. α = mergesort(⟨a1 , a2 , . . . , a⌊n/2⌋ ⟩)
3. β = mergesort(⟨a⌊n/2⌋+1 , a⌊n/2⌋+2 , . . . , an ⟩)
4. return merge(α, β)
5. else return A
9
Merge Sort. Merging Two Sorted Lists
Algorithm: merge
Input: Two sorted lists A and B
Output: Merged sorted list of A and B
10
Analysis of Merge Sort
11
Example: Sorting the sequence ⟨7, 0, 3, 2, 1, 5⟩
7 0 3 2 1 5
7 0 3 2 1 5
7 0 3 2 1 5
7 0 3 2 1 5
7 0 3 2 1 5
0 3 7 1 2 5
0 1 2 3 5 7
12
Finding Maximum
13
Finding Maximum
Algorithm: dc-max
Input: A sequence ⟨a1 , a2 , . . . , an ⟩ of n unordered elements
Output: ak such that ∀i, ai < ak or −∞ if n = 0
1. if n = 1 then return a1
2. else if n < 1 then return −∞
3. else
4. m1 =dc-max(⟨a1 , . . . , a⌊n/2⌋ ⟩)
5. m1 =dc-max(⟨a⌊n/2⌋+1 , . . . , an ⟩)
6. return max{m1 , m2 }
14
Matrix Multiplcation
• Let C = A × B, then
" # " #
c11 c12 a11 · b11 + a11 · b21 a11 · b12 + a12 · b22
C= =
c21 c22 a21 · b11 + a22 · b21 a21 · b12 + a22 · b22
15
Matrix Multiplcation
16
Matrix Multiplcation: Strassen’s Algorithm
17
Integer Multiplcation
• The product
z = xy = xL yL · 2n + (xL yR + xR yL ) · 2n/2 + xR yR
• Requires 4 multiplications of n/2-bit numbers
• We can reduce the number of multiplications to 3
• As following:
xL yR + xR yL = (xL + xR ) · (yL + yR ) − xL yL − xR yR
= xL yL + xL yR + xR yL + xR yR − xL yL − xR yR
= x L yL + x R yR
• Now:
z = xL yL ·2n +((xL +xR )·(yL +yR )−xL yL −xR yR )·2n/2 +xR yR
• The running time T (n) of Karatsuba’s algorithm is:
n
T (n) = 3T + O(n) = O(nlog2 3 ) ≈ O(n1.585 )
2 19