Convex Hull construction¶
In this article we will discuss the problem of constructing a convex hull from a set of points.
Consider $N$ points given on a plane, and the objective is to generate a convex hull, i.e. the smallest convex polygon that contains all the given points.
We will see the Graham's scan algorithm published in 1972 by Graham, and also the Monotone chain algorithm published in 1979 by Andrew. Both are $\mathcal{O}(N \log N)$, and are asymptotically optimal (as it is proven that there is no algorithm asymptotically better), with the exception of a few problems where parallel or online processing is involved.
Graham's scan Algorithm¶
The algorithm first finds the bottom-most point $P_0$. If there are multiple points with the same Y coordinate, the one with the smaller X coordinate is considered. This step takes $\mathcal{O}(N)$ time.
Next, all the other points are sorted by polar angle in clockwise order. If the polar angle between two or more points is the same, the tie should be broken by distance from $P_0$, in increasing order.
Then we iterate through each point one by one, and make sure that the current point and the two before it make a clockwise turn, otherwise the previous point is discarded, since it would make a non-convex shape. Checking for clockwise or anticlockwise nature can be done by checking the orientation.
We use a stack to store the points, and once we reach the original point $P_0$, the algorithm is done and we return the stack containing all the points of the convex hull in clockwise order.
If you need to include the collinear points while doing a Graham scan, you need another step after sorting. You need to get the last group of the sorted vector, that is the points collinear with $P_0$ and the final point. The points on this ray should be reversed so that we can output all the collinear points, otherwise the algorithm would get the nearest point in this line and bail. This step shouldn't be included in the non-collinear version of the algorithm, otherwise you wouldn't get the smallest convex hull.
Implementation¶
struct pt {
double x, y;
bool operator == (pt const& t) const {