Published by Dimitris Kougioumtzis · Updated
Sweep in x order and prune pairs outside the best squared-distance window.
Sort indices by x coordinate, scan earlier candidates inside the current squared-distance window, and retain the lexicographically first original-index pair among ties.
When to use Closest pair by x sweep
Finding nearby point pairs and teaching safe distance-based pruning.
Choosing an alternative
A balanced active-set sweep can achieve O(n log n). This bounded insertion-sort and reverse-scan teaching implementation is O(n^2), even though many candidates are pruned.
Worked example: input and state changes
Example input
0,0;4,0;2,2;3,2;0,4
These checkpoints follow the actual example timeline. State details show the stored values and decisions; use the visualization to inspect every intervening step.
Step 0: Exact integer predicates; equal scale on both coordinate axes.
State at this checkpoint
{ "values": [ 0, 1, 2, 3, 4 ], "active": [], "kind": "graph", "points": [ [ 0, 0 ], [ 4, 0 ], [ 2, 2 ], [ 3, 2 ], [ 0, 4 ] ], "nodeLabels": [ "0 (0, 0)", "1 (4, 0)", "2 (2, 2)", "3 (3, 2)", "4 (0, 4)" ], "directed": false, "chosen": [], "visited": [], "result": 0, "output": [] }Step 2: Compare squared distance 8; incumbent 8.
State at this checkpoint
{ "values": [ 0, 1, 2, 3, 4 ], "active": [ 2, 4 ], "kind": "graph", "points": [ [ 0, 0 ], [ 4, 0 ], [ 2, 2 ], [ 3, 2 ], [ 0, 4 ] ], "nodeLabels": [ "0 (0, 0)", "1 (4, 0)", "2 (2, 2)", "3 (3, 2)", "4 (0, 4)" ], "directed": false, "chosen": [ 0 ], "visited": [], "result": 0, "output": [] }Step 4: Compare squared distance 1; incumbent 1.
State at this checkpoint
{ "values": [ 0, 1, 2, 3, 4 ], "active": [ 3, 2 ], "kind": "graph", "points": [ [ 0, 0 ], [ 4, 0 ], [ 2, 2 ], [ 3, 2 ], [ 0, 4 ] ], "nodeLabels": [ "0 (0, 0)", "1 (4, 0)", "2 (2, 2)", "3 (3, 2)", "4 (0, 4)" ], "directed": false, "chosen": [ 0 ], "visited": [], "result": 0, "output": [] }Step 6: Skip outside the vertical distance window.
State at this checkpoint
{ "values": [ 0, 1, 2, 3, 4 ], "active": [ 1, 3 ], "kind": "graph", "points": [ [ 0, 0 ], [ 4, 0 ], [ 2, 2 ], [ 3, 2 ], [ 0, 4 ] ], "nodeLabels": [ "0 (0, 0)", "1 (4, 0)", "2 (2, 2)", "3 (3, 2)", "4 (0, 4)" ], "directed": false, "chosen": [], "visited": [], "result": 0, "output": [] }Step 8: Closest pair 2, 3, squared distance 1.
State at this checkpoint
{ "values": [ 0, 1, 2, 3, 4 ], "active": [ 2, 3 ], "kind": "graph", "points": [ [ 0, 0 ], [ 4, 0 ], [ 2, 2 ], [ 3, 2 ], [ 0, 4 ] ], "nodeLabels": [ "0 (0, 0)", "1 (4, 0)", "2 (2, 2)", "3 (3, 2)", "4 (0, 4)" ], "directed": false, "chosen": [ 0 ], "visited": [], "result": 1, "output": [ 2, 3 ] }
Expected final state
Closest pair 2, 3, squared distance 1.
Complexity and input bounds
Family: Geometry. Time complexity: O(n^2) bounded sorting and active scan.
Implementation detail: n 0..24, integer coordinates -20..20. Return squared distance and write two original indices; fewer than two points return -1 and [-1,-1]. Input arrays are unchanged. Both views preserve the coordinate aspect ratio. Independent fixtures cover degeneracies and deterministic outcomes in all nine languages.
Space complexity: O(n) index storage for closest-pair sweep; O(1) predicate state otherwise, excluding inputs and saved frames.
Working-space bounds describe algorithm state and any explicitly noted output, excluding the visualization's saved timeline. Recording frames can use more memory than running the function alone. Here n is sequence length, V and E are vertex and edge counts, and other parameters refer to the named input dimensions.
2..24 x,y points separated by ;, integers -20..20. Return squared distance and lexicographically first original-index pair.
The playground validates these limits before starting. Downloaded functions are callable implementations, with parameter and output-buffer contracts in their comments; they do not all repeat the playground's input validation.
Common mistakes and limitations
Squared distances avoid square roots. Keep duplicate coordinates, inspect equal-distance candidates for tie handling, and stop the horizontal scan only when its squared separation is strictly greater than the incumbent.
Further reading
For background on algorithm analysis and the JavaScript function interface:
- MIT OpenCourseWare: algorithm design and analysis foundations
- MDN: JavaScript function parameters and return values
Editorial and testing approach · Browse all algorithm guides
Complete JavaScript implementation
1 2 3 4 5 6 7 8 9 | // Closest pair: n 0..24, integer x/y -20..20. Return exact squared distance, output lexicographically first original-index pair. For n<2 return -1 and write [-1,-1]. Input coordinates unchanged. Stable insertion sorting and reverse active scan are O(n^2) worst case, O(n) scratch; no balanced-tree or O(n log n) claim. Reference snippets assume validated playground inputs. Fixed scratch buffers have 256 slots. Sorting variants may use a different traversal strategy than the animation. function algorithm(x, y, n, output) { output[0] = -1; output[1] = -1; if (n < 2) { return -1; } let order = Array(256).fill(0); let key = 0; let cursor = 0; let best = 3201; let a = 0; let b = 0; let u = 0; let v = 0; let dx = 0; let dy = 0; let distance = 0; for (let i = 0; i < n; i++) { order[i] = i; } for (let i = 1; i < n; i++) { key = order[i]; cursor = i-1; while (cursor >= 0 && (x[order[cursor]] > x[key] || (x[order[cursor]] == x[key] && y[order[cursor]] > y[key]))) { order[cursor+1] = order[cursor]; cursor--; } order[cursor+1] = key; } for (let i = 1; i < n; i++) { a = order[i]; for (let j = i-1; j >= 0; j--) { b = order[j]; dx = x[a]-x[b]; dy = y[a]-y[b]; if (dx*dx > best) { break; } if (dy*dy > best) { continue; } distance = dx*dx+dy*dy; u = a; v = b; if (u > v) { u = b; v = a; } if (distance < best || (distance == best && (u < output[0] || (u == output[0] && v < output[1])))) { best = distance; output[0] = u; output[1] = v; } } } return best; } |
Source
Related foundational closest-point research, not a claim to reproduce its optimal algorithm. This playground uses a bounded quadratic x sweep with exact squared-distance pruning.
- Closest-point problems
Michael Ian Shamos; Dan Hoey (1975). Related research paper.