Closest Pair of Points Implementation in Rust
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 Rust as in every other language.
- ✓f64 carries hypot, powi, INFINITY and total_cmp, the last giving the IEEE 754 total order that sorting coordinates needs.
- ✓sort_by_key(|p| p.y) does not compile here: the key type must be Ord and f64 is only PartialOrd.
- ✓The Rust trap: The borrow checker is what makes this algorithm awkward in Rust and in none of the other seven.
- ✓Indexing strip[j] inside the successor scan emits a bounds check per access; strip[i + 1..].iter().take_while(..) gives the optimiser the same information with no unsafe.
What Closest Pair of Points actually is
Closest Pair of Points in Rust: what you actually reach for
Rust implementation
#[derive(Clone, Copy, Debug)]
pub struct Point { pub x: f64, pub y: f64 }
fn d2(a: Point, b: Point) -> f64 {
let (dx, dy) = (a.x - b.x, a.y - b.y);
dx * dx + dy * dy
}
/// Returns the distance of the closest pair (`f64::INFINITY` for fewer than 2 points).
pub fn closest_pair(pts: &[Point]) -> f64 {
let mut px = pts.to_vec();
px.sort_unstable_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y)));
solve(&px).0.sqrt() // the one sqrt, outside every loop
}
// returns (best squared distance, the same points ordered by y)
fn solve(px: &[Point]) -> (f64, Vec<Point>) {
let n = px.len();
if n <= 3 {
let mut best = f64::INFINITY;
for i in 0..n {
for j in i + 1..n {
best = best.min(d2(px[i], px[j]));
}
}
let mut ys = px.to_vec();
ys.sort_unstable_by(|a, b| a.y.total_cmp(&b.y));
return (best, ys);
}
let mid = n / 2;
let split = px[mid].x;
let (lx, rx) = px.split_at(mid);
let (lb, ly) = solve(lx);
let (rb, ry) = solve(rx);
let mut best = lb.min(rb);
let mut ys = Vec::with_capacity(n);
let (mut i, mut j) = (0usize, 0usize);
while i < ly.len() || j < ry.len() {
if j == ry.len() || (i < ly.len() && ly[i].y <= ry[j].y) {
ys.push(ly[i]);
i += 1;
} else {
ys.push(ry[j]);
j += 1;
}
}
let strip: Vec<Point> = ys
.iter()
.copied()
.filter(|p| (p.x - split) * (p.x - split) < best)
.collect();
// an index loop, not take_while: that closure borrows `best` for the whole
// loop body while the body assigns to it - error[E0506].
for k in 0..strip.len() {
let p = strip[k];
for &q in &strip[k + 1..] {
let dy = q.y - p.y;
if dy * dy >= best {
break;
}
best = best.min(d2(p, q));
}
}
(best, ys)
}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 Rust-specific trap
Performance in Rust, beyond the O(n log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Closest Pair of Points?
f64 carries hypot, powi, INFINITY and total_cmp, the last giving the IEEE 754 total order that sorting coordinates needs. Slices give sort_unstable_by (pattern-defeating quicksort, no allocation) and sort_by (stable, allocates scratch), plus split_at and split_at_mut to hand out the two halves without copying, and windows for the successor scan. std::cmp::Ordering is the comparator result. Nothing in std does spatial indexing; when the exact pair is only step one, the crates people land on are rstar or kiddo.
What is the most common Rust mistake when implementing Closest Pair of Points?
The borrow checker is what makes this algorithm awkward in Rust and in none of the other seven. The textbook version keeps one y-sorted scratch buffer and hands overlapping windows of it to both recursive calls - two &mut into the same Vec, which will not compile. split_at_mut solves the disjoint case, but the merge step wants to read both halves while writing the parent range of that same buffer, so you need either two buffers alternating per level or an owned Vec returned upward. Reaching for RefCell compiles and then panics at runtime with already borrowed: BorrowMutError on the second borrow_mut - the mirror-image already mutably borrowed: BorrowError is what a plain borrow() gets while the mutable one is still live.
How does Closest Pair of Points actually perform in Rust?
Indexing strip[j] inside the successor scan emits a bounds check per access; strip[i + 1..].iter().take_while(..) gives the optimiser the same information with no unsafe. sort_unstable_by avoids the roughly n/2 element scratch that sort_by allocates, and the comparator is monomorphised and inlined, so there is no indirect call per comparison the way there is behind a Go func value or a Java Comparator. f64::hypot rescales to avoid overflow; comparing squared distances skips it entirely. No GC, so the only allocations are the ones you wrote. 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 trialBefore paying for Devin, check its student and free-tier options 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.