Week 5
Week 5
Algorithms
Shahid Hussain
Week 5: September 16, 18: Fall 2024
1
Divide and Conquer Algorithms
Maximum Subarray Sum
2
Maximum Subarray Sum: Trivial Solution
Algorithm: bruteforce-max-subarray-sum
Input: An array A[1..n] of n numbers
Output: The maximum subarray sum M(A)
1. M = −∞
2. for i = 1 to n
3. for j = i to n
4. s=0
5. for k = i to j
6. s = s + A[k]
7. if s > M then M = s
8. return M
5
Maximum Subarray Sum: Divide and Conquer
Algorithm: max-crossing-sum
Input: An array A[l..h] of numbers
Output: The max crossing sum
8
Closest-Pair Problem: Divide and Conquer
• We set δ = min{δL , δR }
• If there is a pair of points pi ∈ PL and
pj ∈ PR such that d(pi , pj ) < δ then this
is the closest pair
δ δ
δ
• If the closest pair consists of some point
in PL and PR then we need to check
only those points that are within δ
distance from the line l (both sides)
• We can now run a linear scan to find
the closest pair in this region from top
to bottom (see the figure)
9
Closest-Pair Problem: Divide and Conquer
10
Fast Fourier Transform
Multiplying polynomials
11
Representating Polynomials
400
60
10
200
0 40
0
−10
20
−200
−20
0 −400
−30
−6 −4 −2 0 2 4 6 −6 −4 −2 0 2 4 6 −6 −4 −2 0 2 4 6
12
Polynomial Multiplication
13
Polynomial Multiplication
• We see that:
A(x) = Ae (x2 ) + xAo (x2 )
where Ae (·) and Ao (·) are polynomials of degree ≤ n/2 − 1
of even- and odd-numbered coefficients, respectively
14
Polynomial Multiplication
15
Polynomial Multiplication
15
Polynomial Multiplication
ω2,8
ω3,8 ω1,8
Imaginary
ω4,8 θ
b z = a + bi ω0,8
θ ω5,8 ω7,8
Real
a ω6,8
16
Fast Fourier Transform
(ωj,2n )2 for j = 0, . . . , 2n − 1
17
Fast Fourier Transform
• From values:
18
Fast Fourier Transform
19
Fast Fourier Transform
2
• We know ωj,2n = e2πji/2n
• Therefore,
2n−1 2n−1
!
X X
2πi(lm+jl)/2n
D(ωj,2n ) = cl e
l=0 m=0
2n−1 2n−1
!
X X
m
= cl (ωl+j,2n )
l=0 m=0
20
Fast Fourier Transform
21
Fast Fourier Transform
Algorithm: recursive-fft
Input: Coefficients of A(x) = ⟨a0 , a1 , . . . , an−1 ⟩
Output: The discrete FFT of of A(x)
1. if n = 1 then return a0
2. ωn = e2πi/n , ω = 1
3. Ae = ⟨a0 , a2 , . . . , an−2 ⟩, Ao = ⟨a1 , a3 , . . . , an−1 ⟩
4. Ye = recursive-fft(Ae ), Yo = recursive-fft(Ao )
5. for k = 0 to n/2 − 1
6. yk = Ye [k] + ωYo [k]
7. yk+n/2 = Ye [k] − ωYo [k]
8. ω = ω · ωn
9. return Y = ⟨y0 , y1 , . . . , yn−1 ⟩
22
Fast Fourier Transform
···
y0 1 1 1 1 a0
y1
1 ω1,n ω2,n ··· ωn−1,n
a1
y2 1 ω2,n ω4,n ··· ω2(n−1),n a2
=
.. .. .. .. .. .. ..
. . . . . . .
yn−1 1 ωn−1,n ω2(n−1),n ··· ω(n−1)(n−1),n an−1
23