The Wayback Machine - https://web.archive.org/web/20240926154735/https://www.geeksforgeeks.org/convex-hull-algorithm/
Open In App

Convex Hull Algorithm

Last Updated : 08 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Convex Hull Algorithm is used to find the convex hull of a set of points in computational geometry. The convex hull is the smallest convex set that encloses all the points, forming a convex polygon. This algorithm is important in various applications such as image processing, route planning, and object modeling.

What is Convex Hull?

The convex hull of a set of points in a Euclidean space is the smallest convex polygon that encloses all of the points. In two dimensions (2D), the convex hull is a convex polygon, and in three dimensions (3D), it is a convex polyhedron.

The below image shows a 2-D convex polygon:

Convex-Hull

Problem Statement: Given an array of coordinates {x, y} on a 2-D plain, your task is to print the set of coordinates that form the convex hull.

Examples:

Input: points[] = {(0, 0), (0, 4), (-4, 0), (5, 0), (0, -6), (1, 0)};
Output: (-4, 0), (5, 0), (0, -6), (0, 4)

Input: points_list = {{1, 2}, {3, 1}, {5, 6}}
Output: {{1, 2}, {3, 1}, {5, 6}}

Convex Hull using Divide and Conquer Algorithm:

Pre-requisite: Tangents between two convex polygons 

Algorithm: Given the set of points for which we have to find the convex hull. Suppose we know the convex hull of the left half points and the right half points, then the problem now is to merge these two convex hulls and determine the convex hull for the complete set.

  • This can be done by finding the upper and lower tangent to the right and left convex hulls. This is illustrated here Tangents between two convex polygons Let the left convex hull be a and the right convex hull be b.
  • Then the lower and upper tangents are named as 1 and 2 respectively, as shown in the figure. Then the red outline shows the final convex hull.

Final-Convex-Hull

  • Now the problem remains, how to find the convex hull for the left and right half. Now recursion comes into the picture, we divide the set of points until the number of points in the set is very small, say 5, and we can find the convex hull for these points by the brute algorithm.
  • The merging of these halves would result in the convex hull for the complete set of points. Note: We have used the brute algorithm to find the convex hull for a small number of points and it has a time complexity of O(N^3).
  • But some people suggest the following, the convex hull for 3 or fewer points is the complete set of points. This is correct but the problem comes when we try to merge a left convex hull of 2 points and right convex hull of 3 points, then the program gets trapped in an infinite loop in some special cases.
  • So, to get rid of this problem I directly found the convex hull for 5 or fewer points by O(N^3) algorithm, which is somewhat greater but does not affect the overall complexity of the algorithm. 

Convex Hull using Jarvis’ Algorithm or Wrapping:

Pre-requisite: How to check if two given line segments intersect?

The idea of Jarvis’s Algorithm is simple, we start from the leftmost point (or point with minimum x coordinate value) and we keep wrapping points in counterclockwise direction. 

The big question is, given a point p as current point, how to find the next point in output? 

The idea is to use orientation() here. Next point is selected as the point that beats all other points at counterclockwise orientation, i.e., next point is q if for any other point r, we have “orientation(p, q, r) = counterclockwise”. 

Algorithm:

  • Initialize p as leftmost point. 
  • Do following while we don’t come back to the first (or leftmost) point. 
    • The next point q is the point, such that the triplet (p, q, r) is counter clockwise for any other point r. To find this, we simply initialize q as next point, then we traverse through all points. For any point i, if i is more counter clockwise, i.e., orientation(p, i, q) is counter clockwise, then we update q as i. Our final value of q is going to be the most counter clockwise point. 
    • next[p] = q (Store q as next of p in the output convex hull). 
    • p = q (Set p as q for next iteration).

Convex-Hull-using-Jarvis-Algorithm-or-Wrapping

Convex Hull using Graham Scan:

Pre-requisite: How to check if two given line segments intersect?

Algorithm: Let points[0..n-1] be the input array. Then the algorithm can be divided into two phases:

Phase 1 (Sort points): We first find the bottom-most point. The idea is to pre-process points be sorting them with respect to the bottom-most point. Once the points are sorted, they form a simple closed path (See the following diagram). 

Convex-Hull-using-Graham-Scan-1

What should be the sorting criteria? computation of actual angles would be inefficient since trigonometric functions are not simple to evaluate. The idea is to use the orientation to compare angles without actually computing them (See the compare() function below)

Phase 2 (Accept or Reject Points): Once we have the closed path, the next step is to traverse the path and remove concave points on this path. How to decide which point to remove and which to keep? Again, orientation helps here. The first two points in sorted array are always part of Convex Hull. For remaining points, we keep track of recent three points, and find the angle formed by them. Let the three points be prev(p), curr(c) and next(n). If orientation of these points (considering them in same order) is not counterclockwise, we discard c, otherwise we keep it. Following diagram shows step by step process of this phase.

Convex-Hull-using-Graham-Scan-2

Convex Hull | Monotone Chain Algorithm:

Monotone chain algorithm constructs the convex hull in O(n * log(n)) time. We have to sort the points first and then calculate the upper and lower hulls in O(n) time. The points will be sorted with respect to x-coordinates (with respect to y-coordinates in case of a tie in x-coordinates), we will then find the left most point and then try to rotate in clockwise direction and find the next point and then repeat the step until we reach the rightmost point and then again rotate in the clockwise direction and find the lower hull.

Quickhull Algorithm for Convex Hull:

The QuickHull algorithm is a Divide and Conquer algorithm similar to QuickSort. Let a[0…n-1] be the input array of points. Following are the steps for finding the convex hull of these points.

Algorithm:

  • Find the point with minimum x-coordinate lets say, min_x and similarly the point with maximum x-coordinate, max_x.
  • Make a line joining these two points, say L. This line will divide the whole set into two parts. Take both the parts one by one and proceed further.
  • For a part, find the point P with maximum distance from the line L. P forms a triangle with the points min_x, max_x. It is clear that the points residing inside this triangle can never be the part of convex hull.
  • The above step divides the problem into two sub-problems (solved recursively). Now the line joining the points P and min_x and the line joining the points P and max_x are new lines and the points residing outside the triangle is the set of points. Repeat point no. 3 till there no point left with the line. Add the end points of this point to the convex hull.

Complexity Analysis for Convex Hull Algorithm:

The below table enlists the time complexities of the above mentioned convex hull algorithms.
where, N denotes the total number of given points.

Convex Hull Algorithm

Time Complexity

Convex Hull using Divide and Conquer Algorithm

O(N*log N)

Convex Hull using Jarvis’ Algorithm or Wrapping

O(N2)

Convex Hull using Graham Scan

 O(N*logN)

Convex Hull using Monotone chain algorithm

O(N*log(N)) 

Convex Hull using Quickhull Algorithm

The analysis is similar to Quick Sort. On average, we get time complexity as O(N*log N), but in worst case, it can become O(N2)

Problems on Convex Hull:

Problem links

Dynamic Convex hull | Adding Points to an Existing Convex Hull

Deleting points from Convex Hull

Perimeter of Convex hull for a given set of points

Check if the given point lies inside given N points of a Convex Polygon

Tangents between two Convex Polygons

Check if given polygon is a convex polygon or not

Check whether two convex regular polygon have same center or not

Minimum Enclosing Circle

Frequently Asked Questions on Convex Hull:

Question 1: What is a convex hull?

Answer: A convex hull is the smallest convex polygon that contains a given set of points.

Question 2: How do you find the convex hull of a set of points?

Answer: There are several algorithms for finding the convex hull of a set of points, such as Graham’s scan, Jarvis’s march, and QuickHull.

Question 3: What are the properties of a convex hull?

Answer: A convex hull is a convex polygon, which means that all of its interior angles are less than 180 degrees. It is also the smallest convex polygon that contains the given set of points.

Question 4: What are the applications of convex hulls?

Answer: Convex hulls have many applications in computer graphics, computational geometry, and other fields. They can be used for:

  • Collision detection
  • Image processing
  • Motion planning
  • Terrain modeling

Question 4: How do you compute the area of a convex hull?

Answer: The area of a convex hull can be computed using the shoelace formula.

Question 5: How do you check if a point is inside a convex hull?

Answer: There are several ways to check if a point is inside a convex hull, such as using the point-in-polygon algorithm or the winding number algorithm.



Similar Reads

Dynamic Convex hull | Adding Points to an Existing Convex Hull
Given a convex hull, we need to add a given number of points to the convex hull and print the convex hull after every point addition. The points should be in anti-clockwise order after addition of every point. Examples: Input : Convex Hull : (0, 0), (3, -1), (4, 5), (-1, 4) Point to add : (100, 100) Output : New convex hull : (-1, 4) (0, 0) (3, -1)
15 min read
Convex Hull | Monotone chain algorithm
Given a set of points, the task is to find the convex hull of the given points. The convex hull is the smallest convex polygon that contains all the points. Please check this article first: Convex Hull | Set 1 (Jarvis’s Algorithm or Wrapping) Examples: Input: Points[] = {{0, 3}, {2, 2}, {1, 1}, {2, 1}, {3, 0}, {0, 0}, {3, 3}} Output: (0, 0) (3, 0)
12 min read
Quickhull Algorithm for Convex Hull
Given a set of points, a Convex hull is the smallest convex polygon containing all the given points. Input : points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}};Output : The points in convex hull are: (0, 0) (0, 3) (3, 1) (4, 4)Input : points[] = {{0, 3}, {1, 1}Output : Not PossibleThere must be at least three points to form
14 min read
Convex Hull using Jarvis' Algorithm or Wrapping
Given a set of points in the plane. the convex hull of the set is the smallest convex polygon that contains all the points of it. We strongly recommend to see the following post first. How to check if two given line segments intersect?The idea of Jarvis's Algorithm is simple, we start from the leftmost point (or point with minimum x coordinate valu
14 min read
Convex Hull using Divide and Conquer Algorithm
In computational geometry, a convex hull is the smallest convex polygon that contains a given set of points. It is a fundamental concept with applications in various fields such as computer graphics, robotics, and image processing. Importance of Convex Hull:Convex hulls are important in computational geometry for several reasons: Collision detectio
15 min read
Perimeter of Convex hull for a given set of points
Given n 2-D points points[], the task is to find the perimeter of the convex hull for the set of points. A convex hull for a set of points is the smallest convex polygon that contains all the points. Examples: Input: points[] = {{0, 3}, {2, 2}, {1, 1}, {2, 1}, {3, 0}, {0, 0}, {3, 3}} Output: 12 Input: points[] = {{0, 2}, {2, 1}, {3, 1}, {3, 7}} Out
10 min read
Deleting points from Convex Hull
Given a fixed set of points. We need to find convex hull of given set. We also need to find convex hull when a point is removed from the set. Example: Initial Set of Points: (-2, 8) (-1, 2) (0, 1) (1, 0) (-3, 0) (-1, -9) (2, -6) (3, 0) (5, 3) (2, 5) Initial convex hull:- (-2, 8) (-3, 0) (-1, -9) (2, -6) (5, 3)Point to remove from the set : (-2, 8)F
15+ min read
Convex Hull in Python
The Convex Hull Algorithm is used to find the convex hull of a set of points in computational geometry. The convex hull is the smallest convex set that encloses all the points, forming a convex polygon. This algorithm is important in various applications such as image processing, route planning, and object modeling. What is Convex Hull?The convex h
15+ min read
Quickhull for Convex hull in Python
Quickhull is an efficient algorithm used to find the convex hull of a set of points in a plane. It works by recursively dividing the point set into two subsets and finding the convex hull for each subset. Quickhull Algorithm for Convex hull:Base Case:If the set of points has 0 or 1 elements, it is already the convex hull.Find the Endpoints:Find the
3 min read
Convex Hull using Graham Scan
Prerequisite: How to check if two given line segments intersect?Jarvis’s Algorithm A convex hull is the smallest convex polygon that contains a given set of points. It is a useful concept in computational geometry and has applications in various fields such as computer graphics, image processing, and collision detection. A convex polygon is a polyg
15+ min read
Number of ways a convex polygon of n+2 sides can split into triangles by connecting vertices
Given a convex polygon with n+2 sides. The task is to calculate the number of ways in which triangles can be formed by connecting vertices with non-crossing line segments.Examples: Input: n = 1 Output: 1 It is already a triangle so it can only be formed in 1 way.Input: n = 2 Output: 2 It can be cut into 2 triangles by using either pair of opposite
5 min read
Check whether two convex regular polygon have same center or not
Given two positive integers N and M which denotes the sides of the convex regular polygon where N < M, the task is to check whether polygons have the same center or not if N-sided polygon was inscribed in an M-sided polygon.Center of Polygon: Point inside a polygon which is equidistant from each vertex of the polygon. Examples: Input: N = 9, M =
3 min read
Check if given polygon is a convex polygon or not
Given a 2D array point[][] with each row of the form {X, Y}, representing the co-ordinates of a polygon in either clockwise or counterclockwise sequence, the task is to check if the polygon is a convex polygon or not. If found to be true, then print "Yes" . Otherwise, print "No". In a convex polygon, all interior angles are less than or equal to 18
9 min read
Find number of diagonals in n sided convex polygon
Given n > 3, find number of diagonals in n sided convex polygon.According to Wikipedia, In geometry, a diagonal is a line segment joining two vertices of a polygon or polyhedron, when those vertices are not on the same edge. Informally, any sloping line is called diagonal. Examples :  Input : 5Output : 5Explanation: Five possible diagonals are :
3 min read
Tangents between two Convex Polygons
Given two convex polygons, we need to find the lower and upper tangents to these polygons. As shown in the figure below, [Tex]T_{RL}      [/Tex]and [Tex]T_{LR}      [/Tex]show upper and lower tangent respectively.  Examples:   Input : First Polygon : {(2, 2), (3, 3), (5, 2), (4, 0), (3, 1)} Second Polygon : {(-1, 0), (0, 1), (1, 0), (0, -2)}.Output
15+ min read
Check if the given point lies inside given N points of a Convex Polygon
Given coordinates of the N points of a Convex Polygon. The task is to check if the given point (X, Y) lies inside the polygon. Examples: Input: N = 7, Points: {(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)}, Query: X = 3, Y = 2 Below is the image of plotting of the given points: Output: YES Input: N = 7, Points: {(1, 1), (2, 1), (3, 1), (4
15 min read
Edge Relaxation Property for Dijkstra’s Algorithm and Bellman Ford's Algorithm
In the field of graph theory, various shortest path algorithms especially Dijkstra’s algorithm and Bellmann-Ford’s algorithm repeatedly employ the use of the technique called Edge Relaxation. The idea of relaxation is the same in both algorithms and it is by understanding, the 'Relaxation property' we can fully grasp the working of the two algorith
4 min read
Difference between Greedy Algorithm and Divide and Conquer Algorithm
Greedy algorithm and divide and conquer algorithm are two common algorithmic paradigms used to solve problems. The main difference between them lies in their approach to solving problems. Greedy Algorithm:The greedy algorithm is an algorithmic paradigm that follows the problem-solving heuristic of making the locally optimal choice at each stage wit
3 min read
Algorithm Library | C++ Magicians STL Algorithm
For all those who aspire to excel in competitive programming, only having a knowledge about containers of STL is of less use till one is not aware what all STL has to offer. STL has an ocean of algorithms, for all < algorithm > library functions : Refer here.Some of the most used algorithms on vectors and most useful one's in Competitive Prog
7 min read
What is the stupidest sorting algorithm? (Worst Sorting Algorithm)
Bogo sort stands out as the undisputed champion of stupidity. Unlike other sorting algorithms that follow a structured approach, Bogo sort relies on sheer luck and randomness to achieve its goal. How Bogo Sort Works?Bogo sort operates on the following principle: Randomly shuffle the elements in the list.Check if the list is sorted.If the list is no
2 min read
Difference Between Dijkstra's Algorithm and A* Search Algorithm
Dijkstra's Algorithm and A* Algorithm are two of the most widely used techniques. Both are employed to the find the shortest path between the nodes in a graph but they have distinct differences in their approaches and applications. Understanding these differences is crucial for the selecting the appropriate algorithm for the given problem. What is
3 min read
Z algorithm (Linear time pattern searching Algorithm)
This algorithm efficiently locates all instances of a specific pattern within a text in linear time. If the length of the text is "n" and the length of the pattern is "m," then the total time taken is O(m + n), with a linear auxiliary space. It is worth noting that the time and auxiliary space of this algorithm is the same as the KMP algorithm, but
13 min read
Karatsuba algorithm for fast multiplication using Divide and Conquer algorithm
Given two binary strings that represent value of two integers, find the product of two strings. For example, if the first bit string is "1100" and second bit string is "1010", output should be 120. For simplicity, let the length of two strings be same and be n. A Naive Approach is to follow the process we study in school. One by one take all bits o
15+ min read
Reversal algorithm for Array rotation
Given an array arr[] of size N, the task is to rotate the array by d position to the left. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7}, d = 2Output: 3, 4, 5, 6, 7, 1, 2Explanation: If the array is rotated by 1 position to the left, it becomes {2, 3, 4, 5, 6, 7, 1}.When it is rotated further by 1 position,it becomes: {3, 4, 5, 6, 7, 1, 2} Input:
15 min read
Block swap algorithm for array rotation
Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. Rotation of the above array by 2 will make an array Algorithm : Initialize A = arr[0..d-1] and B = arr[d..n-1] 1) Do following until size of A is equal to size of B a) If A is shorter, divide B into Bl and Br such that Br is of same length as A. Swap A and Br to change
15+ min read
Boruvka's algorithm for Minimum Spanning Tree
Following two algorithms are generally taught for Minimum Spanning Tree (MST) problem. Prim's algorithm Kruskal's algorithm There is a third algorithm called Boruvka's algorithm for MST which (like the above two) is also Greedy algorithm. The Boruvka's algorithm is the oldest minimum spanning tree algorithm was discovered by Boruvka in 1926, long b
1 min read
Introduction to Push Relabel Algorithm
Given a graph which represents a flow network where every edge has a capacity. Also given two vertices source ‘s’ and sink ‘t’ in the graph, find the maximum possible flow from s to t with following constraints: Flow on an edge doesn’t exceed the given capacity of the edge. Incoming flow is equal to outgoing flow for every vertex except s and t. Fo
6 min read
An in-place algorithm for String Transformation
Given a string, move all even positioned elements to the end of the string. While moving elements, keep the relative order of all even positioned and odd positioned elements the same. For example, if the given string is "a1b2c3d4e5f6g7h8i9j1k2l3m4", convert it to "abcdefghijklm1234567891234" in-place and in O(n) time complexity. Below are the steps
15+ min read
Union By Rank and Path Compression in Union-Find Algorithm
In the previous post, we introduced union find algorithm and used it to detect cycles in a graph. We used the following union() and find() operations for subsets. C/C++ Code // Naive implementation of find int find(int parent[], int i) { if (parent[i] == -1) return i; return find(parent, parent[i]); } // Naive implementation of union() void Union(i
15+ min read
Closest Pair of Points using Divide and Conquer algorithm
We are given an array of n points in the plane, and the problem is to find out the closest pair of points in the array. This problem arises in a number of applications. For example, in air-traffic control, you may want to monitor planes that come too close together, since this may indicate a possible collision. Recall the following formula for dist
15+ min read
Practice Tags :