Closest Point (implemented in Java)
Recent point:
In the n points on the two-dimensional plane, the nearest point is quickly located.
Java implementation:
Package p2; import static java. lang. math. *; import java. util. arrayList; import java. util. arrays; import java. util. collections; import java. util. comparator; import java. util. extends; public class CloestPair {// coordinate static class Point {public Point () {} public Point (double x, double y) {this. x = x; this. y = y;} double x; double y;} public static void main (String [] args) {dynamic partition = new partition (System. in); while (true) {int n = random. nextInt (); Point [] ps = new Point [n]; for (int I = 0; I <n; I ++) {double x = random. nextDouble (); double y = bytes. nextDouble (); ps [I] = new Point (x, y);} // sort Arrays in ascending order based on the x axis coordinates. sort (ps, new Comparator
() {@ Overridepublic int compare (Point o1, Point o2) {if (o1.x <o2.x) return-1; if (o1.x> o2.x) return 1; if (o1.y <o2.y) return-1; if (o1.y> o2.y) return 1; return 0 ;}}); double minDis = minDistance (ps, 0, n-1); System. out. println (minDis );}} /*** minimum distance between points ** @ param ps * @ param l * @ param r * @ return */public static double minDistance (Point [] ps, int l, int r) {/*** the same point. if no point exists, the distance cannot be 0, and the maximum value */if (l = r) {return Double is returned. MAX_VALUE;} if (l + 1 = r) {return distance (ps [l], ps [r]);} int center = l + (r-l) /2; double dis1 = minDistance (ps, l, center); double dis2 = minDistance (ps, center + 1, r); double minDis = min (dis1, dis2); ArrayList
NearPoints = new ArrayList <> (); // select a Point for (Point p: ps) {if (abs (ps [center]. x-p. x) <= minDis) {nearPoints. add (p) ;}/// sort Collections by Y axis in ascending order. sort (nearPoints, new Comparator
() {@ Overridepublic int compare (Point o1, Point o2) {if (o1.y <o2.y) return-1; if (o1.y> o2.y) return 1; if (o1.x <o2.x) return-1; if (o1.x> o2.x) return 1; return 0 ;}}); for (int I = 0; I <nearPoints. size (); I ++) {for (int j = I + 1; j <nearPoints. size (); j ++) {if (nearPoints. get (j ). y-nearPoints. get (I ). y> minDis) {break; // The element y + 1 is farther away from element I and there is no need to continue to compare} double d = distance (nearPoints. get (j), nearPoints. get (I); if (d <minDis) {minDis = d ;}}return minDis;} public static double distance (Point p1, Point p2) {if (p1 = p2) return 0; return sqrt (pow (p1.x-p2.x, 2) + pow (p1.y-p2.y, 2 ));}}