-
Notifications
You must be signed in to change notification settings - Fork 0
/
Smallest distance between pair of points
122 lines (99 loc) · 2.45 KB
/
Smallest distance between pair of points
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include<iostream>
#include<stdio.h>
#include <bits/stdc++.h>
using namespace std;
//class to declare the point's coordinates
class Point
{
public:
int x, y;
};
//sort x coordinates
int sort_x(const void* a, const void* b)
{
Point *p1 = (Point *)a, *p2 = (Point *)b;
return (p1->x - p2->x);
}
//sort y coordinates
int sort_y(const void* a, const void* b)
{
Point *p1 = (Point *)a, *p2 = (Point *)b;
return (p1->y - p2->y);
}
//euclidian distance calcualtion
float euclidian_dist(Point p1, Point p2)
{
float dist,x,y;
x=p1.x-p2.x;
y=p1.y=p2.y;
dist = sqrt(pow(x, 2) + pow(y, 2));
return dist;
}
//Brute force method
float BF_method(Point P[], int n)
{
int i,j;
float min;
min=FLT_MAX;
for (i = 0; i < n; i++)
for (j = i+1; j < n; j++)
if (euclidian_dist(P[i], P[j]) < min)
min = euclidian_dist(P[i], P[j]);
return min;
}
//Finding the minimum value
float min(float x, float y)
{
if (x<y)
return x;
else
return y;
}
//Finding the closest distance, on the basis of sorting the y-coordinates
float closest_distance(Point R[], int n, float d)
{
int i,j;
float min;
min=d;
qsort(R, n, sizeof(Point), sort_y);
for (i = 0; i < n; i++)
for (j = i+1; j < n && ((R[j].y - R[i].y) < min); j++)
if (euclidian_dist(R[i],R[j]) < min)
min = euclidian_dist(R[i], R[j]);
return min;
}
//Choosing and performing the appropriate method
float method(Point P[], int n)
{
int i,j;
float d_left, d_right,d;
if(n<=3)
return BF_method(P, n);
// finding the middle value
int mid=n/2;
Point mid_p=P[mid];
d_right=method(P + mid, n - mid);
d_left=method(P, mid);
d=min(d_left,d_right);
//Array of points that are closer to the middle line within the minimum disatnce d
Point R[n];
j=0;
for (i = 0; i < n; i++)
if (abs(P[i].x - mid_p.x) < d)
{ R[j] = P[i];
j++;
}
return min(d, closest_distance(R, j, d) );
}
float closest(Point P[], int n)
{
qsort(P, n, sizeof(Point), sort_x);
return method(P, n);
}
int main()
{
Point P[] = {{1, 3}, {12, 20}, {30, 40}, {4, 2}, {8, 15}, {2, 5}};
int n = sizeof(P) / sizeof(P[0]);
cout << "Smallest distance: "<<method(P, n);
return 0;
}