// A recursive function to find the smallest distance. The array P contains // all points sorted according to x coordinate float closestUtil(Point P[], int n) { // If there are 2 or 3 points, then use brute force if (n <= 3) return bruteForce(P, n); // Find the middle point int mid = n/2; Point midPoint = P[mid]; // Consider the vertical line passing through the middle point // calculate the smallest distance dl on left of middle point and // dr on right side float dl = closestUtil(P, mid); float dr = closestUtil(P + mid, n-mid); // Find the smaller of two distances float d = min(dl, dr); // Build an array strip[] that contains points close (closer than d) // to the line passing through the middle point Point strip[n]; int j = 0; for (int i = 0; i < n; i++) if (abs(P[i].x - midPoint.x) < d) strip[j] = P[i], j++; // Find the closest points in strip. Return the minimum of d and closest // distance is strip[] return min(d, stripClosest(strip, j, d) ); }
// The main functin that finds the smallest distance // This method mainly uses closestUtil() float closest(Point P[], int n) { qsort(P, n, sizeof(Point), compareX); // Use recursive function closestUtil() to find the smallest distance return closestUtil(P, n); }
float closestUtil(Point P[], int n) { if (n <= 3) return bruteForce(P, n); int mid = n/2; Point midPoint = P[mid]; float dl = closestUtil(P, mid); float dr = closestUtil(P + mid, n-mid); float d = min(dl, dr); Point strip[n]; int j = 0; for (int i = 0; i < n; i++) if (abs(P[i].x - midPoint.x) < d) strip[j] = P[i], j++; return min(d, stripClosest(strip, j, d) ); }
float closest(Point P[], int n) { qsort(P, n, sizeof(Point), compareX); return closestUtil(P, n); }