Monotone chain convex hull

Andrew's Monotone Chain Convex Hull algorithm is an algorithm which constructs convex hull of a set of 2D points in $$O(n log n)$$ time.

It does this by first sorting the points lexicographically (first by x-coordinate, and in case of a tie, by y-coordinate), and then constructing upper and lower hulls of the points in $$O(n)$$ time.

An upper hull is the part of the convex hull, which is visible from the above. It runs from its rightmost point to the leftmost point in counterclockwise order. Lower hull is the remaining part of the convex hull.



Pseudo-code
Input: a list P of points in the plane.

Sort the points of P by x-coordinate (in case of a tie, sort by y-coordinate). Remove points, which have same coordinates.

Initialize U and L as empty lists. The lists will hold the vertices of upper and lower hulls respectively.

for i := 1 to n do   while L contains at least two points and the sequence of last two points in L and P[i] does not make a counter-clockwise turn, remove the last point from L   append P[i] to L

for i := n downto 1 do   while U contains at least two points and the sequence of last two points in U and P[i] does not make a counter-clockwise turn, remove the last point from U   append P[i] to U

Remove the first point from U and the last point from L Concatenation of L and U gives the convex hull of P.

Implementations
C++