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
|
#include <float.h>
#include <math.h>
#include <stdio.h>
typedef struct Point2D
{
double x;
double y;
}Point2D;
inline double distance(Point2D* p1, Point2D* p2)
{
return sqrt((p1->x - p2->x)*(p1->x - p2->x) + (p1->y - p2->y)*(p1->y - p2->y));
}
double brute_search(Point2D* p, const unsigned len)
{
if(len < 2) return DBL_MAX;
//find the min distance between 3 or 2 points
double min_distance = DBL_MAX;
for(int i = 0; i < len - 1; ++i)
for(int j = i + 1; j < len; ++j)
{
double d = distance(&p[i], &p[j]);
if(d < min_distance) min_distance = d;
}
return min_distance;
}
double closest_pair(Point2D* pX, Point2D* pY, const unsigned start, const unsigned end)
{
const unsigned midd_x = (end ) / 2;
//base case
if((end - start) <= 3) return brute_search(pX, (end - start));
double xr_min = closest_pair(pX, 0, start, midd_x);
double xl_min = closest_pair(pX + midd_x, 0, midd_x , end);
double x_min = xr_min < xl_min ? xr_min : xl_min;
return x_min;
}
int main(void)
{
Point2D points[] = {
{.x = 3.0f, .y = 2.0f},
{.x = 3.0f, .y = 5.0f},
{.x = 8.0f, .y = 2.5f},
{.x = 8.1f, .y = 2.5f},
{.x = 8.5f, .y = 5.0f},
{.x = 8.7f, .y = 5.0f},
{.x = 8.9f, .y = 5.0f},
{.x = 8.9f, .y = 7.0f},
};
printf("%.3f is closest distance\n", closest_pair(points, 0,0,sizeof(points)/sizeof(points[0])));
return 0;
}
|