Talk:Closest-pair problem/C: Difference between revisions

(→‎Propose replacing code: clean up a bit)
Line 16:
typedef struct { double x, y; } point_t, *point;
 
/* note: even though l_list and r_list are used by each recursion of closest(), they
they are always used in sequencesequentially, no need to allocate them repeatedly */
int *l_list, *r_list;
 
Line 32:
 
 
double brute_force(point pts, int max_n, intpoint *a, intpoint *b)
{
int i, j;
point pi;
double d, min_distmin_d = MAXDOUBLE;
 
for (i = 0, pi = pts; i < max_n; pi++, i++) {
for (j = i + 1; j < max_n; j++) {
if ( (d = dist(pi, pts + j)) < min_dist ) {;
if (d >= min_d ) *a = icontinue;
 
*b = j;
min_dist*a = dpi;
}*b = pts + j;
*bmin_d = jd;
}
}
return min_distmin_d;
}
 
Line 64 ⟶ 65:
double min_d, d, dsqrt, median;
 
/* don'tproblem dividesmall ifenough, there arendon't enoughdivide, pointsjust to divideconquer */
if (n =<= 28) {return brute_force(pts, n, a, b);
*a = pts;
*b = pts + 1;
return dist(pts, pts + 1);
}
 
if (n == 3) {
min_d = dist(pts, pts + 1);
*a = pts; *b = pts + 1;
 
if (min_d > (d = dist(pts, pts + 2))) {
min_d = d;
*b = pts + 2;
}
if (min_d > (d = dist(pts + 1, pts + 2))) {
min_d = d;
*a = pts + 1;
*b = pts + 2;
}
return min_d;
}
 
/* get left and right results */
left = right = n / 2;
if ((min_d = closest(pts, left, a, b)) > (d = closest(pts + left, n - left, &a1, &b1))) {;
d = brute_forceclosest(pts + left, NPn - left, &ia1, &jb1);
 
if (nmin_d ==> 3d) {
min_d = d;
*a = a1;
Line 98 ⟶ 82:
dsqrt = sqrt(min_d);
 
/* find points within +- min distance on X from the center line, list their indices */
list their indices }*/
for ( lsize = 0, left--;
median - pts[left].x < dsqrt && left;
Line 142 ⟶ 127:
int main(int argc, char **argv)
{
int i, j;
double d;
point a, b;
 
Line 155 ⟶ 139:
}
 
/*
d = brute_force(pts, NP, &i, &j);
printf("brute force: %g, between", sqrt(%fbrute_force(pts,%f) andNP, (%f&a,%f &b)\n",));
printf("between (%f,%f) and d(%f,%f)\n", pts[i].a->x, pts[i].a->y, pts[j].a->x, pts[j].a->y);
*/
 
 
int cmp_x(const void *a, const void *b) {
Anonymous user