




Sponsored
Sponsored
The Monotone Chain Algorithm is an efficient algorithm for finding the convex hull of a set of 2D points. It constructs the hull in O(n log n) time. The idea is to sort the points, then construct the lower and upper hulls in O(n) time each. Points are rejected if they don't form a 'left turn', which can be determined using cross product.
Time complexity is O(n log n) due to sorting. Space complexity is O(n) for storing the hull points.
1def cross(o, a, b):
2    return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
3
4def convex_hull(points):
5    points = sorted(points)
6    if len(points) <= 1:
7        return points
8
9    lower = []
10    for p in points:
11        while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
12            lower.pop()
13        lower.append(p)
14
15    upper = []
16    for p in reversed(points):
17        while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
18            upper.pop()
19        upper.append(p)
20
21    return lower[:-1] + upper[:-1]
22
23if __name__ == '__main__':
24    trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]
25    result = convex_hull(trees)
26    print("Convex Hull:")
27    for point in result:
28        print(point)This Python code implements the Monotone Chain Algorithm to find the convex hull. The sorted points are divided into lower and upper hulls, with each hull being pruned for points that would create a non-left turn.
The Gift Wrapping Algorithm, also known as Jarvis March, is another method to find the convex hull. It builds the hull one vertex at a time, looking for the line tangent to the current edge and a point in the set of all remaining points. It's less efficient than Monotone Chain, operating in O(nh) time complexity, where h is the number of hull vertices.
Time complexity is O(nh) where n is the number of points and h is the number of points on the hull. Space complexity is O(h) for the hull array.
1
This C implementation of the Gift Wrapping Algorithm iteratively chooses the most counterclockwise point until it returns to the start point. It determines orientation by calculating the cross product and compares relative angles.