V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Closest Pair of Points

Divide and conquer with a narrow cross-boundary strip

Improve on checking every pair

Comparing every pair of n planar points takes O(n^2) time. The divide-and-conquer algorithm first sorts points by x-coordinate, splits them at the median, and recursively finds the closest pair in each half.

The merge step must inspect the boundary

Let delta be the better distance from the two halves. A closer pair with one point on each side must lie inside a strip of width 2 * delta around the midline. Sort those strip points by y-coordinate; each point only needs comparisons with the next few points whose y-gap is smaller than the current best distance.

The player shows the midline, the active strip, each candidate segment, and the best pair. In this data set the final closest pair crosses the split, which demonstrates why the merge step cannot stop after solving the two halves.

Plot 8 points sorted by x; divide and conquer will improve on the O(n^2) pair scan.

1function closest(pts: Pt[]): number { // pts sorted by x
2 if (pts.length <= 3) return brute(pts);
3 const mid = pts.length >> 1;
4 const midX = (pts[mid - 1].x + pts[mid].x) / 2; // midline
5 const dl = closest(pts.slice(0, mid)); // recurse on the left half
6 const dr = closest(pts.slice(mid)); // recurse on the right half
7 let d = Math.min(dl, dr); // δ
8 const strip = pts.filter(p => Math.abs(p.x - midX) < d)
9 .sort((a, b) => a.y - b.y); // sort the delta strip by y
10 for (let i = 0; i < strip.length; i++)
11 for (let j = i + 1; j < strip.length &&
12 strip[j].y - strip[i].y < d; j++) // compare neighbors with y-gap < delta
13 d = Math.min(d, dist(strip[i], strip[j])); // a cross-strip pair may improve d
14 return d;
15}
Points8
Best distance-
1 / 10

Linear merge work per recursion level

A packing argument bounds the number of relevant y-neighbors by a constant. With points kept in y-order during merging, each recursion level costs O(n), giving T(n) = 2T(n/2) + O(n) = O(n log n) time and O(n) auxiliary space.

Merge invariant: before scanning the strip, the current best is already correct for all pairs that lie completely inside either half.

Compare this distance-based divide and conquer with the orientation tests in Convex Hull, or revisit ordered merging in Merge Sort.