11package com .thealgorithms .randomized ;
2- import java .util .*;
32import java .math .BigDecimal ;
43import java .math .RoundingMode ;
5- /**
6- * This class implements the randomized Closest Pair Algorithm; given some number of points
7- * in a plane find the pair with minimum euclidean distance from each other. This solution
8- * uses the divide and conquer approach.
9- * @author Bri Harris
10- */
11-
124import java .util .*;
135
14- class Point implements Comparable <Point > {
6+ final class Point implements Comparable <Point > {
157 double x ;
168 double y ;
179
@@ -30,20 +22,29 @@ static double distance(Point p1, Point p2) {
3022 }
3123}
3224
33- public class ClosestPair {
25+ public final class ClosestPair {
26+
3427 public static double closest (List <Point > points ) {
28+ if (points == null || points .isEmpty ()) {
29+ throw new IllegalArgumentException ("There are no pairs to compare." );
30+ }
31+
32+ if (points .size () == 1 ) {
33+ throw new IllegalArgumentException ("There is only one pair." );
34+ }
35+
3536 Collections .sort (points );
3637 double result = closestRecursiveHelper (points , 0 , points .size () - 1 );
3738
38- //Return distance of closest pair rounded to 2 decimal places
39+ // Return distance of closest pair rounded to 2 decimal places
3940 return new BigDecimal (result ).setScale (2 , RoundingMode .HALF_UP ).doubleValue ();
4041 }
4142
4243 private static double closestRecursiveHelper (List <Point > points , int left , int right ) {
43- //Base Case occurs with 3 or fewer points
44+ // Base Case occurs with 3 or fewer points
4445 if (right - left <= 2 ) return baseCase (points , left , right );
4546
46- //Divide and conquer
47+ // Divide and conquer
4748 int mid = (left + right ) / 2 ;
4849 double midX = points .get (mid ).x ;
4950
@@ -67,15 +68,15 @@ private static double baseCase(List<Point> points, int left, int right) {
6768 }
6869
6970 private static double checkBoundary (List <Point > points , int left , int right , double midX , double minDist ) {
70- //Consider a boundary by the dividing line
71+ // Consider a boundary by the dividing line
7172 List <Point > boundary = new ArrayList <>();
7273 for (int i = left ; i <= right ; i ++) {
7374 if (Math .abs (points .get (i ).x - midX ) < minDist ) {
7475 boundary .add (points .get (i ));
7576 }
7677 }
7778
78- //sort by y coordinate within the boundary and check for closer points
79+ // sort by y coordinate within the boundary and check for closer points
7980 boundary .sort (Comparator .comparingDouble (p -> p .y ));
8081 for (int i = 0 ; i < boundary .size (); i ++) {
8182 for (int j = i + 1 ; j < boundary .size () && (boundary .get (j ).y - boundary .get (i ).y ) < minDist ; j ++) {
0 commit comments