Paradigm
Given a problem of size n divide it into subproblems of size n, a ≥ 1, b > 1. Solve each subproblem recursively. Combine solutions of subproblems to get the overall solution.
T(n) = aT(n/b ) + [work for merge]
Convex Hull
Given n points in plane
S = {(xi, yi) | i = 1, 2,...,n}
assume no two have the same x coodinates, no two have sa`me y coordinates, no three in a line.
Convex Hull: smallest polygon contain all points in the plane.
CH(S) represented by the sequence of points on the boundary in clockwise order as a doubly linked list.
Brute force for Convex Hull
Test each line segment to see if it makes up an edge of the convex hull
- If the rest of the points are on one side of the segment, the segment is on the convex hull.
- else the segment is not.
- O(n2) edges, O(n) tests ⇒ O(n3) complexity
Divide and Conquer Convex Hull
Sort points by x coordinates
- divide into left half A and right half B by x coords
- compute CH(A) and CH(B)
- combine CH's of two halves (merge step)
How to merge?
- Find the upper tangent (ai, bj).
- Find the lower tangent (ak, bm).
- Cut and paste in time Θ(n).
Firstly, link ai to bj, go down b list till you see bm and link bm to ak, continue along the a list until you return to ai.
Find Tangents
Assume ai maximizes x within CH(A) (a1, a2,...,ap). b1 minimizes x within CH(B) (b1, b2,..., bq)
L is the vertical line separating A and B. Define y(i, j) as y-coordinate of intersection between L and segment (ai, bj ).
Claim: (ai, bj ) is upper tangent if it maximizes y(i, j)
If y(i, j) is not maximum, there will be points on both sides of (ai, bj ) and it cannot be a tangent.
Algorithm: Obvious O(n2) algorithm looks at all ai, bj pairs. T(n)=2T(n/2)+ Θ(n^2) = Θ(n^2).
i = 1
j = 1
while(y(i, j+1) > y(i, j) or y(i − 1, j) > y(i, j))
if (y(i, j + 1) > y(i, j)) -> move right finger clockwise
j = j + 1( mod q)
else
i = i - 1( mod p) -> move left finger anti-cloclwise
return (ai, bj ) as upper tangent
T(n)=2T(n/2) + Θ(n) = Θ(n log n)
Median Finding
Given a set of n numbers, define rank(x) as the number of numbers in the set that are ≤ x. Find an element of rank (lower median) and (upper median).
Select(S, i)
Pick x in S
Compute k = rank(x)
B = {y ∈ S|y<x}
C = {y ∈ S|y>x}
if k = i
return x
else if k > i
return Select(B, i)
else if k < i
return Select(C, i - k)
Picking x Cleverly
Need to pick x so rank(x) is not extreme.
- Arrange S into columns of size 5 (n/5 cols)
- Sort each column (bigger elements on top) (linear time)
- Find “median of medians” as x