Divide N Conquer
Divide N Conquer
ALGORITHMS
a problem of size n
subproblem 1 subproblem 2
of size n/2 of size n/2
a solution to a solution to
subproblem 1 subproblem 2
a solution to
the original problem
DIVIDE-AND-CONQUER EXAMPLES
• Split array A[0..n-1] in two about equal halves and make copies of
each half in arrays B and C
• Sort arrays B and C recursively
• Merge sorted arrays B and C into array A as follows:
• Repeat the following until no elements remain in one of the arrays:
8 3 2 9 7 1 5 4
8 3 2 9 7 1 5 4
8 3 2 9 71 5 4
8 3 2 9 7 1 5 4
3 8 2 9 1 7 4 5
2 3 8 9 1 4 5 7
1 2 3 4 5 7 8 9
ANALYSIS OF MERGESORT
A[i]p A[i]p
• Exchange the pivot with the last element in the first (i.e., ) subarray
— the pivot is now in its final position
• Sort the two subarrays recursively
HOARE’S PARTITIONING ALGORITHM
ANALYSIS OF QUICKSORT
• Improvements:
• better pivot selection: median of three partitioning
• switch to insertion sort on small subfiles
• elimination of recursion
These combine to 20-25% improvement
Efficiency: Θ(n)
BINARY TREE ALGORITHMS (CONT.)
TL TR
Efficiency: Θ(n)
M U LT I P L I C AT I O N O F L A R G E I N T E G E R S
A = 12345678901357986429 B = 87654321284820912836
2135 4014
STRASSEN’S MATRIX
MULTIPLICATION
Strassen observed [1969] that the product of two matrices can be
computed as follows:
FORMUL AS FOR STRASSEN’S ALGORITHM
Number of multiplications:
M(n) = 7M(n/2), M(1) = 1
Solution: M(n) = 7log 2n = nlog 27 ≈ n2.807 vs. n3 of brute-force alg.
dl
d
r
d d
CLOSEST PAIR BY DIVIDE-AND-CONQUER (CONT.)
Step 2 Find recursively the closest pairs for the left and right
subsets.
Step 3 Set d = min{dl, dr}
We can limit our attention to the points in the symmetric
vertical strip S of width 2d as possible closest pair. (The
points are stored and processed in increasing order of
their y coordinates.)
Step 4 Scan the points in the vertical strip S from the lowest up.
For every point p(x,y) in the strip, inspect points in
in the strip that may be closer to p than d. There can be
no more than 5 such points following p on the strip list!
EFFICIENCY OF THE CLOSEST-PAIR
ALGORITHM
P2
P1
EFFICIENCY OF QUICKHULL
ALGORITHM