From 49a54952870923042d6eda83597f22d4b36199f8 Mon Sep 17 00:00:00 2001 From: NIHIT SAHA Date: Fri, 1 Oct 2021 16:39:18 +0530 Subject: [PATCH] Create Closest pair of points - Geometrical Algorithms --- ...st pair of points - Geometrical Algorithms | 133 ++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 C++/Closest pair of points - Geometrical Algorithms diff --git a/C++/Closest pair of points - Geometrical Algorithms b/C++/Closest pair of points - Geometrical Algorithms new file mode 100644 index 00000000..74231ae9 --- /dev/null +++ b/C++/Closest pair of points - Geometrical Algorithms @@ -0,0 +1,133 @@ +#include +#include +#include +#include +using namespace std; + + +struct Point +{ + int x, y; +}; + + + +int compareX(const void* a, const void* b) +{ + Point *p1 = (Point *)a, *p2 = (Point *)b; + return (p1->x != p2->x) ? (p1->x - p2->x) : (p1->y - p2->y); +} + +int compareY(const void* a, const void* b) +{ + Point *p1 = (Point *)a, *p2 = (Point *)b; + return (p1->y != p2->y) ? (p1->y - p2->y) : (p1->x - p2->x); +} + + +float dist(Point p1, Point p2) +{ + return sqrt( (p1.x - p2.x)*(p1.x - p2.x) + + (p1.y - p2.y)*(p1.y - p2.y) + ); +} + + +float bruteForce(Point P[], int n) +{ + float min = FLT_MAX; + for (int i = 0; i < n; ++i) + for (int j = i+1; j < n; ++j) + if (dist(P[i], P[j]) < min) + min = dist(P[i], P[j]); + return min; +} + + +float min(float x, float y) +{ + return (x < y)? x : y; +} + + +float stripClosest(Point strip[], int size, float d) +{ + float min = d; // Initialize the minimum distance as d + + + for (int i = 0; i < size; ++i) + for (int j = i+1; j < size && (strip[j].y - strip[i].y) < min; ++j) + if (dist(strip[i],strip[j]) < min) + min = dist(strip[i], strip[j]); + + return min; +} + + +float closestUtil(Point Px[], Point Py[], int n) +{ + + if (n <= 3) + return bruteForce(Px, n); + + + int mid = n/2; + Point midPoint = Px[mid]; + + + + Point Pyl[mid]; // y sorted points on left of vertical line + Point Pyr[n-mid]; // y sorted points on right of vertical line + int li = 0, ri = 0; // indexes of left and right subarrays + for (int i = 0; i < n; i++) + { + if ((Py[i].x < midPoint.x || (Py[i].x == midPoint.x && Py[i].y < midPoint.y)) && li