Chapter 2 Devide and Conquer
Chapter 2 Devide and Conquer
Divide-and-Conquer
Divide-and-Conquer
a problem of size n
(instance)
subproblem 1 subproblem 2
of size n/2 of size n/2
a solution to a solution to
subproblem 1 subproblem 2
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
8 3 2 9 71 5 4
2 3 8 9 1 4 5 7
1 2 3 4 5 7 8 9
Analysis of Mergesort
T(n) = have
• All cases 2T(n/2) + Θ(n),
same T(1) = 0 Θ(n log n)
efficiency:
• Exchange the pivot with the last element in the first (i.e., ) subarray —
A[i]p A[i]p
the pivot is now in its final position
• Sort the two subarrays recursively
Partitioning Algorithm
or i > r
or j = l
<
5 3 1 9 8 2 4 7
2 3 1 4 5 8 9 7
1 2 3 4 5 7 8 9
1 2 3 4 5 7 8 9
1 2 3 4 5 7 8 9
1 2 3 4 5 7 8 9
Analysis of Quicksort
• Best case: split in the middle — Θ(n log n)
• Worst case: sorted array! — Θ(n2) T(n) = T(n-1) + Θ(n)
• Average case: random arrays — Θ(n log n)
• Improvements:
• better pivot selection: median of three partitioning
• switch to insertion sort on small subfiles
• elimination of recursion
These combine to 20-25% improvement
l 0; r n-1
while l r do
m (l+r)/2
if K = A[m] return m
else if K < A[m] r m-1
else l m+1
return -1
Analysis of
• Time efficiency
Binary Search
• worst-case recurrence: Cw (n) = 1 + Cw( n/2 ), Cw (1) = 1
solution: Cw(n) = log2(n+1)
TL TR
A = 12345678901357986429 B = 87654321284820912836
2135 4014
• Brute-force algorithm
c00 c01 a00 a01 b00 b01
= *
c10 c11 a10 a11 b10 b11
m1 + m4 - m5 + m7 m3 + m5
=
m2 + m4 m1 + m3 - m2 + m6
• m1 = (a00 + a11) * (b00 + b11)
• m2 = (a10 + a11) * b00
• m3 = a00 * (b01 - b11)
• m4 = a11 * (b10 - b00)
• m5 = (a00 + a01) * b11
• m6 = (a10 - a00) * (b00 + b01)
7 multiplications
• m7 = (a01 - a11) * (b10 + b11)
18 additions
Strassen’s Matrix Multiplication
Strassen observed [1969] that the product of two matrices can be
computed in general as follows:
M1 + M4 - M5 + M7 M3 + M5
=
M2 + M4 M1 + M3 - M2 + M6
Formulas for Strassen’s Algorithm
M1 = (A00 + A11) (B00 + B11)
Step 1 Divide the points given into two subsets S1 and S2 by a vertical line x =
c so that half the points lie to the left or on the line and half the points
lie to the right or on the line.
Closest Pair by Divide-and-Conquer (cont.)
Step 2 Find recursively the closest pairs for the left and right
subsets.
P2
P1
Efficiency of Quickhull Algorithm
• Finding point farthest away from line P1P2 can be done in linear time
• Time efficiency: T(n) = T(x) + T(y) + T(z) + T(v) + O(n),
where x + y + z +v <= n.
• worst case: Θ(n2) T(n) = T(n-1) + O(n)
• average case: Θ(n) (under reasonable assumptions about
distribution of points given)