Closest Pair of Points Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Closest Pair of Points runs in O(n log n) time and O(n) space, in Java as in every other language.
- ✓java.util.Arrays.sort(T[], Comparator) is a stable TimSort and has the range overload sort(a, fromIndex, toIndex, cmp), so halves can be ordered in place.
- ✓Comparator.comparingDouble(Point::y), never Comparator.comparing(Point::y) - the generic form boxes every coordinate into a Double.
- ✓The Java trap: TimSort checks its own assumptions and throws. A comparator that is not a total order - subtraction-based, or hand-rolled < chains meeting a NaN coordinate - makes Arrays.sort fail with IllegalArgumentException: Comparison method violates its general contract!, thrown from inside java.util.TimSort.
- ✓Point[] is an array of references: each distance dereferences two objects that may sit anywhere in the heap, and each object carries a header, so a million points cost far more than the 16 MB of coordinates.
What Closest Pair of Points actually is
Closest Pair of Points in Java: what you actually reach for
Java implementation
import java.util.Arrays;
import java.util.Comparator;
public final class ClosestPair {
public record Point(double x, double y) {}
private static final Comparator<Point> BY_X =
Comparator.comparingDouble(Point::x).thenComparingDouble(Point::y);
private static final Comparator<Point> BY_Y = Comparator.comparingDouble(Point::y);
private static double sq(double v) { return v * v; }
private static double d2(Point a, Point b) {
return sq(a.x() - b.x()) + sq(a.y() - b.y());
}
/** Returns the squared distance of the closest pair. */
public static double closest(Point[] pts) {
Point[] px = pts.clone();
Arrays.sort(px, BY_X);
return rec(px);
}
/** Returns the best squared distance and leaves px ordered by y. */
private static double rec(Point[] px) {
int n = px.length;
if (n <= 3) {
double best = Double.POSITIVE_INFINITY;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) best = Math.min(best, d2(px[i], px[j]));
Arrays.sort(px, BY_Y);
return best;
}
int mid = n >>> 1;
double split = px[mid].x();
Point[] l = Arrays.copyOfRange(px, 0, mid);
Point[] r = Arrays.copyOfRange(px, mid, n);
double best = Math.min(rec(l), rec(r));
merge(l, r, px);
Point[] strip = new Point[n];
int m = 0;
for (Point p : px) if (sq(p.x() - split) < best) strip[m++] = p;
for (int i = 0; i < m; i++)
for (int j = i + 1; j < m; j++) {
if (sq(strip[j].y() - strip[i].y()) >= best) break;
best = Math.min(best, d2(strip[i], strip[j]));
}
return best;
}
private static void merge(Point[] a, Point[] b, Point[] out) {
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length)
out[k++] = a[i].y() <= b[j].y() ? a[i++] : b[j++];
while (i < a.length) out[k++] = a[i++];
while (j < b.length) out[k++] = b[j++];
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Closest Pair of Points?
java.util.Arrays.sort(T[], Comparator) is a stable TimSort and has the range overload sort(a, fromIndex, toIndex, cmp), so halves can be ordered in place. Build the comparator with Comparator.comparingDouble(Point::x), the primitive-specialised factory. Math.hypot and Double.POSITIVE_INFINITY cover the arithmetic, and java.awt.geom.Point2D really does expose static distance(x1, y1, x2, y2) and distanceSq(x1, y1, x2, y2) if you want the squared form without writing it. A record Point(double x, double y) is the modern carrier.
What is the most common Java mistake when implementing Closest Pair of Points?
TimSort checks its own assumptions and throws. A comparator that is not a total order - subtraction-based, or hand-rolled < chains meeting a NaN coordinate - makes Arrays.sort fail with IllegalArgumentException: Comparison method violates its general contract!, thrown from inside java.util.TimSort. It only fires once a run exceeds the minimum merge length, so every unit test with a dozen points passes and the 100k-point job dies. Worse, it surfaces at the sort rather than at the NaN, so the stack trace points nowhere near the parser that produced it.
How does Closest Pair of Points actually perform in Java?
Point[] is an array of references: each distance dereferences two objects that may sit anywhere in the heap, and each object carries a header, so a million points cost far more than the 16 MB of coordinates. There are no value types to fix that; the layout escape hatch is two double[] arrays plus an index permutation, which is ugly and roughly twice as fast. The inner loop needs thousands of iterations before C2 compiles it, so a single-shot timing measures the interpreter. BY_X and BY_Y are different lambda classes, so the compare call site inside java.util.TimSort sees two receivers; C2 still inlines a bimorphic site behind a type guard, so that is cheap, and the cliff is megamorphic - three or more comparators through the same sort. What static final fields actually buy is constant-folding of the comparator at your own call sites, and one allocation instead of a fresh lambda per recursion level. If you need a genuinely monomorphic compare, write the merge or the sort yourself against a single comparator. Time complexity is O(n log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Replit free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.