Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Closest Pair of Points Implementation in Java

19 min readadvanced
Website QA and SEO audits

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

Given n points in the plane, the closest pair is the two with the smallest Euclidean distance between them. Brute force is O(n^2); the divide-and-conquer solution sorts by x, splits at the median, recurses on both halves, then repairs the boundary by scanning a vertical strip of width 2d ordered by y, where each point only has to be compared with a constant number of successors. Working engineers reach for it in collision detection, de-duplicating GPS fixes, seeding clusters and validating meshes, usually as the exact check sitting behind a spatial index.

Closest Pair of Points in Java: what you actually reach for

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.

Java implementation

Comparator.comparingDouble(Point::y), never Comparator.comparing(Point::y) - the generic form boxes every coordinate into a Double. A comparator written as (int)(a.x() - b.x()) is an instant rejection: the cast truncates, so every pair closer than 1.0 apart compares equal and the median split lands somewhere arbitrary. Reviewers also want the comparators hoisted into static final fields so each call site stays monomorphic, and Arrays.copyOfRange or the range-sort overload instead of a stream collect in the recursion.
java
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 Free

The Java-specific 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. 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.

Performance in Java, beyond the O(n log n)

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. The asymptotic cost is the same in every language, O(n log n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Closest Pair of Points between languages.

Real-World Applications

Closest Pair of Points applies wherever its problem shape appears in your own code. In Java, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Closest Pair of Points helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Closest Pair of Points appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Closest Pair of Points over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Closest Pair of Points to build pattern recognition. In Java, demonstrate proficiency with generics and streams API to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Java code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? Replit free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.