8000 Quick Hull · glitches-coder/Algorithms@b772671 · GitHub
[go: up one dir, main page]

Skip to content

Commit b772671

Browse files
Quick Hull
1 parent 3e0bcb2 commit b772671

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
#define iPair pair<int, int>
5+
6+
// Stores the result (points of convex hull)
7+
set<iPair> hull;
8+
9+
int findSide(iPair p1, iPair p2, iPair p)
10+
{
11+
int val = (p.second - p1.second) * (p2.first - p1.first) -
12+
(p2.second - p1.second) * (p.first - p1.first);
13+
14+
if (val > 0)
15+
return 1;
16+
if (val < 0)
17+
return -1;
18+
return 0;
19+
}
20+
21+
int lineDist(iPair p1, iPair p2, iPair p)
22+
{
23+
return abs ((p.second - p1.second) * (p2.first - p1.first) -
24+
(p2.second - p1.second) * (p.first - p1.first));
25+
}
26+
27+
void quickHull(iPair a[], int n, iPair p1, iPair p2, int side)
28+
{
29+
int ind = -1;
30+
int max_dist = 0;
31+
32+
for (int i=0; i<n; i++)
33+
{
34+
int temp = lineDist(p1, p2, a[i]);
35+
if (findSide(p1, p2, a[i]) == side && temp > max_dist)
36+
{
37+
ind = i;
38+
max_dist = temp;
39+
}
40+
}
41+
42+
if (ind == -1)
43+
{
44+
hull.insert(p1);
45+
hull.insert(p2);
46+
return;
47+
}
48+
49+
quickHull(a, n, a[ind], p1, -findSide(a[ind], p1, p2));
50+
quickHull(a, n, a[ind], p2, -findSide(a[ind], p2, p1));
51+
}
52+
53+
void printHull(iPair a[], int n)
54+
{
55+
if (n < 3)
56+
{
57+
cout << "Convex hull not possible\n";
58+
return;
59+
}
60+
61+
int min_x = 0, max_x = 0;
62+
for (int i=1; i<n; i++)
63+
{
64+
if (a[i].first < a[min_x].first)
65+
min_x = i;
66+
if (a[i].first > a[max_x].first)
67+
max_x = i;
68+
}
69+
70+
quickHull(a, n, a[min_x], a[max_x], 1);
71+
72+
quickHull(a, n, a[min_x], a[max_x], -1);
73+
74+
cout << "The points in Convex Hull are:\n";
75+
while (!hull.empty())
76+
{
77+
cout << "(" <<( *hull.begin()).first << ", "
78+
<< (*hull.begin()).second << ") ";
79+
hull.erase(hull.begin());
80+
}
81+
}
82+
83+
// Driver code example
84+
int main()
85+
{
86+
iPair a[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4},
87+
{0, 0}, {1, 2}, {3, 1}, {3, 3}};
88+
int n = sizeof(a)/sizeof(a[0]);
89+
printHull(a, n);
90+
return 0;
91+
}

0 commit comments

Comments
 (0)
0