Professional Documents
Culture Documents
Combine
Applicability
– Use the divide-and-conquer algorithmic pattern when
ALL of the following are true:
• The problem lends itself to division into sub-problems of the
same type
mergeSort(A) {
if(A.size() <= 1)
return A;
else {
left = A.subList(0, A.size()/2);
right = A.subList(A.size()/2, A.size());
sLeft = mergeSort(left);
sRight = mergeSort(right);
newA = merge(sLeft, sRight);
return newA;
}
MergeSort
3 8 5 4 1 7 6 2
3 8 5 4 1 7 6 2
3 4 5 8 1 2 6 7
1 2 3 4 5 6 7 8
QuickSort
Sort a collection of n items into increasing order
– Algorithm steps:
• Break the list into 2 pieces based on a pivot
– The pivot is usually the first item in the list
• All items smaller than the pivot go in the left and all items larger go
in the right
• Sort each piece (recursion again)
• Combine the results together
QuickSort
3 8 5 4 2 7 6 1
2 1 3 8 5 4 7 6
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
To Develop a Divide & Conquer
Algorithm
1. Determine how to obtain the solution to an instance
from the solution to one or more smaller instances
1 2 3 1 2 3
30 36 42
4 5 6 4 5 6
66 81 96
7 8 9
P1 = A(F – H)
P5 + P4 – P2 + P6 P1 + P2
P2 = (A + B)H X×Y =
P3 + P4 P1 + P5 – P3 – P7
P3 = (C + D)E
P4 = D(G – E)
P5 = (A + D)(E + H)
P6 = (B – D)(G + H)
P7 = (A – C)(E + F)
Closest-Pair Problem
Find the closest pair of points in a collection of n points in
a given plane (use Euclidean distance)
• Assume n = 2k
• If n = 2, answer is distance between these two points
• Otherwise,
– sort points by x-coordinate
– split sorted points into two piles of equal size (i.e., divide
by vertical line l)
• Three possibilities: closest pair is
– in Left side
– in Right side
– between Left and Right side
Applications:
• collision avoidance in robotics;
• mapping the surface of an object (like an asteroid);
• analyzing images of soil particles;
• estimating percentage of lung volume occupied by pneumonia
Convex Hull
QuickHull Algorithm:
• This is actually a half-space hull finder
– You start with the leftmost (A) and rightmost (B) points
and all the points above them
– It finds the half hull to the top side
• One can then find the entire hull by running the same
algorithm on the bottom points
Convex Hull
QuickHull Algorithm:
• Pick the point C that is furthest from the line AB
• Form two lines – AC and CB and place all points above AC into one
list and all points above CB into another list.
Ignore the inner
points
Convex Hull
QuickHull Algorithm:
• Recursively conquer each list of points.
• Conquer each half to get convex hull for that half (stop when
you reach a single point)
Convex Hull
MergeHull Algorithm:
• Combine the 2 small hulls together into 1 large hull
– First find the top and bottom tangent lines to the hulls
» A special “walking” algorithm is used to find the
tangent lines in linear time
– Then use these tangent lines to create the full hull
When to avoid Divide-and-Conquer?