|
| 1 | +package com.thealgorithms.geometry; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public final class ClosestPairOfPoints { |
| 6 | + private ClosestPairOfPoints() {} |
| 7 | + |
| 8 | + public static double closestPair(List<Point> points) { |
| 9 | + List<Point> sortedByX = new ArrayList<>(points); |
| 10 | + sortedByX.sort(Comparator.comparingDouble(p -> p.x)); |
| 11 | + return divide(sortedByX); |
| 12 | + } |
| 13 | + |
| 14 | + private static double divide(List<Point> pts) { |
| 15 | + int n = pts.size(); |
| 16 | + if (n <= 3) return bruteForce(pts); |
| 17 | + |
| 18 | + int mid = n / 2; |
| 19 | + Point midPoint = pts.get(mid); |
| 20 | + |
| 21 | + double dl = divide(pts.subList(0, mid)); |
| 22 | + double dr = divide(pts.subList(mid, n)); |
| 23 | + double d = Math.min(dl, dr); |
| 24 | + |
| 25 | + List<Point> strip = new ArrayList<>(); |
| 26 | + for (Point p : pts) { |
| 27 | + if (Math.abs(p.x - midPoint.x) < d) strip.add(p); |
| 28 | + } |
| 29 | + |
| 30 | + strip.sort(Comparator.comparingDouble(p -> p.y)); |
| 31 | + for (int i = 0; i < strip.size(); ++i) { |
| 32 | + for (int j = i + 1; j < strip.size() && (strip.get(j).y - strip.get(i).y) < d; ++j) { |
| 33 | + d = Math.min(d, strip.get(i).distance(strip.get(j))); |
| 34 | + } |
| 35 | + } |
| 36 | + return d; |
| 37 | + } |
| 38 | + |
| 39 | + private static double bruteForce(List<Point> pts) { |
| 40 | + double min = Double.POSITIVE_INFINITY; |
| 41 | + for (int i = 0; i < pts.size(); ++i) { |
| 42 | + for (int j = i + 1; j < pts.size(); ++j) { |
| 43 | + min = Math.min(min, pts.get(i).distance(pts.get(j))); |
| 44 | + } |
| 45 | + } |
| 46 | + return min; |
| 47 | + } |
| 48 | +} |
0 commit comments