




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.
1function cross(o, a, b) {
2    return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
3}
4
5function convexHull(points) {
6    points.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]);
7    if (points.length <= 1) return points;
8
9    const lower = [];
10    for (let p of points) {
11        while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0)
12            lower.pop();
13        lower.push(p);
14    }
15
16    const upper = [];
17    for (let i = points.length - 1; i >= 0; i--) {
18        let p = points[i];
19        while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0)
20            upper.pop();
21        upper.push(p);
22    }
23
24    upper.pop();
25    lower.pop();
26    return lower.concat(upper);
27}
28
29let trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]];
30console.log("Convex Hull:", convexHull(trees));This JavaScript solution uses the Monotone Chain Algorithm. After sorting the points, it builds the lower and upper hulls using stack operations and combines them to form the complete convex hull, taking care of duplicate endpoints.
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 Java implementation showcases the use of an ArrayList to gather hull points by searching for the next tangential line using the counterclockwise test. The cycle continues until returning to the start vertex.