Closest Pair of Points — Divide and Conquer
Tutorial Video
Text description (accessibility)
This video demonstrates the "Closest Pair of Points — Divide and Conquer" functional Rust example. Difficulty level: Fundamental. Key concepts covered: Functional Programming. Finding the two closest points in a set of n points naively requires O(n^2) distance comparisons. Key difference from OCaml: | Aspect | Rust | OCaml |
Tutorial
The Problem
Finding the two closest points in a set of n points naively requires O(n^2) distance comparisons. Divide-and-conquer solves this in O(n log n): split points by x-coordinate median, recursively find closest pairs in left and right halves, then check the strip of width 2*delta around the dividing line for cross-half pairs. The key insight: within the strip, each point needs to be compared against at most 7 others — a fixed constant, making the strip check O(n) total. This algorithm appears in geographic information systems (nearest neighbor queries), robotics (obstacle proximity), and computational chemistry (molecular interaction detection).
🎯 Learning Outcomes
Code Example
#![allow(clippy::all)]
//! PlaceholderKey Differences
| Aspect | Rust | OCaml |
|---|---|---|
| Array mutation | In-place sort on &mut [Point] | Array.sort (in-place) |
| Splitting | Slice indexing &mut points[..mid] | Array.sub (copies) |
| Strip | Vec<&Point> — references | Point list or Point array |
| Base case size | <= 3 | Same |
| True O(n log n) | Sort by x once, maintain y-order | List.merge approach |
| Parallel variant | rayon::join for halves | No built-in parallel |
OCaml Approach
OCaml sorts with Array.sort and splits using Array.sub. The recursive calls work on sub-arrays. The strip check uses Array.to_list |> List.filter then List.sort by y-coordinate, followed by a sliding window. OCaml's List.fold_left computes the minimum distance in the strip. The functional style returns a new sorted-by-y array at each level (merge-sort style) for the true O(n log n) variant. Float.min combines the two recursive distances.
Full Source
#![allow(clippy::all)]
//! PlaceholderDeep Comparison
OCaml vs Rust: Closest Pair Divide Conquer
Overview
See the example.rs and example.ml files for detailed implementations.
Key Differences
| Aspect | OCaml | Rust |
|---|---|---|
| Type system | Hindley-Milner | Ownership + traits |
| Memory | GC | Zero-cost abstractions |
| Mutability | Explicit ref | mut keyword |
| Error handling | Option/Result | Result<T, E> |
See README.md for detailed comparison.