Closest Pair of Points - Rosetta Code
http://www.cs.ucsb.edu/~suri/cs235/ClosestPair.pdf
Read full article from Closest-pair problem - Rosetta Code
http://www.cs.ucsb.edu/~suri/cs235/ClosestPair.pdf
Theorem
A rectangle of width d and height 2d can contain at most six points such that any two points are at distance at least dpublic static Pair divideAndConquer(List<? extends Point> points) { List<Point> pointsSortedByX = new ArrayList<Point>(points); sortByX(pointsSortedByX); List<Point> pointsSortedByY = new ArrayList<Point>(points); sortByY(pointsSortedByY); return divideAndConquer(pointsSortedByX, pointsSortedByY); } private static Pair divideAndConquer(List<? extends Point> pointsSortedByX, List<? extends Point> pointsSortedByY) { int numPoints = pointsSortedByX.size(); if (numPoints <= 3) return bruteForce(pointsSortedByX); int dividingIndex = numPoints >>> 1; List<? extends Point> leftOfCenter = pointsSortedByX.subList(0, dividingIndex); List<? extends Point> rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints); List<Point> tempList = new ArrayList<Point>(leftOfCenter); sortByY(tempList); Pair closestPair = divideAndConquer(leftOfCenter, tempList); tempList.clear(); tempList.addAll(rightOfCenter); sortByY(tempList); Pair closestPairRight = divideAndConquer(rightOfCenter, tempList); if (closestPairRight.distance < closestPair.distance) closestPair = closestPairRight; tempList.clear(); double shortestDistance =closestPair.distance; double centerX = rightOfCenter.get(0).x; for (Point point : pointsSortedByY) if (Math.abs(centerX - point.x) < shortestDistance) tempList.add(point); for (int i = 0; i < tempList.size() - 1; i++) { Point point1 = tempList.get(i); for (int j = i + 1; j < tempList.size(); j++) { Point point2 = tempList.get(j); if ((point2.y - point1.y) >= shortestDistance) break; double distance = distance(point1, point2); if (distance < closestPair.distance) { closestPair.update(point1, point2, distance); shortestDistance = distance; } } } return closestPair; }Also refer to http://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairDQ.html
Read full article from Closest-pair problem - Rosetta Code