×

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex hull. A rubber band wrapped around a bounded subset of the plane can be used to represent the convex hull as the shape it encloses. The algorithmic concerns of finding the convex hull of a constrained set of points in the plane or other low-dimensional Euclidean spaces, as well as its dual problem of intersecting half-spaces, are fundamental problems in computational geometry. In higher dimensions, they can be solved in a time that corresponds to the worst-case output complexity as stated by the upper limit theorem. They can be solved in time O(nlog n) for two- or three-dimensional point sets. In this article we are going to discuss about convex hull and its algorithm in detail.

What is Convex Hull?

If there are line segments connecting every pair of the points in a set of points in a Euclidean space, the set is said to be convex. The intersection of all half-spaces that contain a set of points S is the convex hull of that set of points. The collection of points on or to one side of a line constitutes a half space in two dimensions. Higher dimensions can be applied to this idea. The group of points on or to one side of a plane constitutes a half-space, and so on. Keep in mind that the convex hull of a set is a closed, "solid" area that contains all of the interior points. Since it is the boundary that we compute and that implies the region, the term is frequently used more loosely in computational geometry to indicate the boundary of this region.

Convex hull Algorithm in C++

Convex Hull Algorithms

For computing the convex hull of a finite set of points, multiple techniques with varying processing difficulties have been suggested in computational geometry. Constructing a clear and effective representation of the necessary convex shape entails computing the convex hull.

The algorithms are as follows:

  1. Chan's algorithm — O(n log h)
  2. Divide and conquer — O(n log n)
  3. Gift wrapping, a.k.a. Jarvis algorithm — O(nh)
  4. Graham scan — O(n log n)
  5. Incremental convex hull algorithm — O(n log n)
  6. Kirkpatrick–Seidel algorithm — O(n log h)
  7. Monotone chain, a.k.a. Andrew's algorithm— O(n log n)
  8. Quickhull- O(nlogn)

Algorithm

Jarvis's algorithm's basic concept is that we wrap points counterclockwise, starting with the leftmost point (or the point with the lowest x-coordinate value). Here, using orientation is the idea. The next point is chosen as the point that outperforms all others when oriented counterclockwise, i.e., the following point is q if "orientation(p, q, r) = counterclockwise" is true for any other point r. Make p the leftmost point at startup. The point q that causes the triplet (p, q, r) to rotate counterclockwise for any other point r is the following point. We just initialise q as the next point and then travel through all of the points to discover this. We update q as I for any point I if I is more counterclockwise or if orientation(p, I q) is counterclockwise. The most counterclockwise point will be our final value for q. In the convex output hull, place q after p. For the following iteration, set p to q.

C++ Example:

//CPP program
#include <bits/stdc++.h>
using namespace std;


struct Mypoint
{
	int x, y;
};
int orientation(Mypoint p, Mypoint q, Mypoint r)
{
	int val = (q.y - p.y) * (r.x - q.x) -
			(q.x - p.x) * (r.y - q.y);


	if (val == 0) return 0; 
	return (val > 0)? 1: 2; 
}
void convexHull(Mypoint pointval[], int n)
{
	if (n < 3) return;
	vector<Mypoint> hull;
	int l = 0;
	for (int i = 1; i < n; i++)
		if (pointval[i].x < pointval[l].x)
			l = i;
	int p = l, q;
	do
	{
		hull.push_back(pointval[p]);
		q = (p+1)%n;
		for (int i = 0; i < n; i++)
		{
		if (orientation(pointval[p], pointval[i], pointval[q]) == 2)
			q = i;
		}
		p = q;


	} while (p != l); 
	for (int i = 0; i < hull.size(); i++)
		cout << "(" << hull[i].x << ", "
			<< hull[i].y << ")\n";
}
int main()
{
	Mypoint pointval[] = {{1, 3}, {1, 2}, {4, 1}, {2, 5},
					{3, 1}, {2, 0}, {3, 2}};
	int n = sizeof(pointval)/sizeof(pointval[0]);
	convexHull(pointval, n);
	return 0;
}


//JAVA program
import java.util.*;


class Mypoint
{
	int x, y;
	Mypoint(int x, int y){
		this.x=x;
		this.y=y;
	}
}


class bn {
	
	public static int orientation(Mypoint p, Mypoint q, Mypoint r)
	{
		int val = (q.y - p.y) * (r.x - q.x) -
				(q.x - p.x) * (r.y - q.y);
	
		if (val == 0) return 0; 
		return (val > 0)? 1: 2; 
	}
	
	public static void convexHull(Mypoint pointval[], int n)
	{
		if (n < 3) return;
		Vector<Mypoint> hull = new Vector<Mypoint>();
	
		int l = 0;
		for (int i = 1; i < n; i++)
			if (pointval[i].x < pointval[l].x)
				l = i;
	
		int p = l, q;
		do
		{
			hull.add(pointval[p]);
	
			q = (p + 1) % n;
			
			for (int i = 0; i < n; i++)
			{
			if (orientation(pointval[p], pointval[i], pointval[q])
												== 2)
				q = i;
			}
	
			p = q;
	
		} while (p != l); 
	
		for (Mypoint temp : hull)
			System.out.println("(" + temp.x + ", " +
								temp.y + ")");
	}
	
	public static void main(String[] args)
	{


		Mypoint pointval[] = new Mypoint[7];
		pointval[0]=new Mypoint(0, 3);
		pointval[1]=new Mypoint(2, 3);
		pointval[2]=new Mypoint(1, 1);
		pointval[3]=new Mypoint(2, 1);
		pointval[4]=new Mypoint(3, 0);
		pointval[5]=new Mypoint(0, 0);
		pointval[6]=new Mypoint(3, 3);
		
		int n = pointval.length;
		convexHull(pointval, n);
		
	}
}


Output:

Convex hull Algorithm in C++

Related Topics

INT_MAX and INT_MIN in C/C++

In competitive programming, assigning a variable that maximum or minimum value a data type can carry is frequently necessary. Still, it might be challenging to recall such a significant, exact...

3 minutes read.

C++ Try-Catch

Every useful program will eventually encounter unexpected outcomes. By entering data that are incorrect, users might create mistakes. Sometimes the program's creator didn't consider all of the options or was...

7 minutes read.

Initialization of Data Members

In this tutorial, we'll look at how to initialise static member variables in C++. Static members, such as functions or variables, can be added to C++ classes. After declaring the...

1 minute read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

Hospital Management Project in C++

The following capabilities are required to build a hospital management project: These are as follows: hospitals' names, contact information, and lists of doctors and patients. Activities Supported Hospital Data Print Patients' data to...

4 minutes read.

C++ Reading file

In file handling, read() function is used to read data from the file into the program. The read() uses ifstream library to read data from a file. Syntax file-stream-class   file-stream-object;   file-stream-object.read((char *)&var , sizeof (var)); <h3">Example ofstream  outfile;         outfile . read((char*)&emp,sizeof(emp)); C++ File Handling read() Function Example Reading the content of existing...

2 minutes read.

Print Table Using While Loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

4 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

Decltype type Specifier in C++

The primary use of C++ decltype is to inspect the declaration type of an entity in an expression. The auto keyword can declare a particular type of variable, whereas the...

4 minutes read.

Random Number Generator in C++

In programming, we need to frequently create the randomly. For example, a dice game, handing out cards to players, apps for rearranging tunes, etc. T There are two tools available in...

4 minutes read.

Private Inheritance in C++

Private inheritance is an inheritance in object-oriented programming (OOP) languages where a subclass derives from a superclass. Still, the derived class does not inherit the public and protected members of...

7 minutes read.

Different Ways to Compare Strings in C++

This section will go over the many methods for comparing strings in the C++ programming language. The string comparison checks if the first string is equal to another string. HELLO...

6 minutes read.

C++ Do while loop

In this article, we will discuss the C++ Do-While loop with its syntax, working, key features, algorithm, and examples. Do-While Loop: The do-while loop constitutes a specific style of looping construct in...

5 minutes read.

Depth First Search Program to Traverse a Graph in C++

Depth First Search (DFS) is a technique that is used for transversing the graph. The process of Depth First Search (DFS) starts from the root node and then next comes...

6 minutes read.

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

How to implement map in C++

Part of the C++ STL is maps (Standard Template Library). Maps are associative containers that hold sorted key-value pairs, where each key is distinct and may only be added or...

4 minutes read.

C++ Deque

Definition: Deque or the Doubly ended queue is a data structure or operation performed under queue where insertion and deletion are allowed at both ends. A deque is an ordered collection of...

5 minutes read.

How to create a table in C++

C++ is a programming language that has evolved as an improvement of c language. It includes an object-oriented archetype. C++ programming language is a compiled language that complies with the...

3 minutes read.

Features of OOPS in C++

What is OOPs? The main reason programmers prefer C ++ language over C is because of the support of object-oriented programing in C++. As the name suggests, object-oriented programming or OOPs...

3 minutes read.