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

→‎Propose replacing code: clean up, removed unneeded "optimizations"
(→‎Propose replacing code: clean up a bit)
(→‎Propose replacing code: clean up, removed unneeded "optimizations")
Line 18:
/* note: even though l_list and r_list are used by each recursion of closest(),
they are always used in sequentially, no need to allocate them repeatedly */
intpoint *l_list, *r_list;
 
inline double dist(point a, point b)
Line 35:
{
int i, j;
point pi;
double d, min_d = MAXDOUBLE;
 
for (i = 0, pi = pts; i < max_n; pi++, i++) {
for (j = i + 1; j < max_n; j++) {
d = dist(pipts + i, pts + j);
if (d >= min_d ) continue;
*a = pipts + i;
 
*a = pi;
*b = pts + j;
min_d = d;
Line 51 ⟶ 49:
}
 
void sort_y(point pts*list, int n, int *list)
{
int cmp_y(const void *a, const void *b) {
return cmp_dbl(pts[* ((int*point)a].)->y, pts[*(int*(point)b].)->y );
}
qsort(list, n, sizeof(intpoint), cmp_y);
}
 
Line 62 ⟶ 60:
{
int left, right, lsize, rsize, i;
point pl, a1, b1;
double min_d, d, dsqrt, median;
 
Line 83 ⟶ 81:
 
/* find points within +- min distance on X from the center line,
list their indicespointers */
for ( lsize = 0, left--;
median - pts[left].x < dsqrt && left;
l_list[lsize++] = pts + left--);
 
for ( rsize = 0;
pts[right].x - median < dsqrt && right < n;
r_list[rsize++] = pts + right++);
 
/* sort the indicespointers by y: don't touch the point data which is sorted by x */
sort_y(ptsl_list, lsize, l_list);
sort_y(ptsr_list, rsize, r_list);
 
/* climb up left and right list and compare distance */
for (left = right = 0; left < lsize; left ++) {
/* next point in left list */
plmedian = pts + l_list[left]->y;
median = pl->y;
 
/* climb up right list until the y is not too low */
while (right < rsize && median > dsqrt + pts[r_list[right]].->y && right < rsize)
right++;
 
Line 110 ⟶ 107:
for (i = right; i < rsize; i++) {
/* right y is too high, break */
if (pts[ r_list[i] ].->y > median + dsqrt) break;
 
if (min_d > (d = dist(pts + r_list[i], pll_list[left]))) {
*a = pll_list[left];
*b = pts + r_list[i];
min_d = d;
dsqrt = sqrt(min_d);
Line 131 ⟶ 128:
 
point pts = malloc(sizeof(point_t) * NP);
l_list = malloc(sizeof(intpoint) * (NP / 2));
r_list = malloc(sizeof(intpoint) * ((NP + 1) / 2));
 
for(i = 0; i < NP; i++) {
Anonymous user