Algorithm 1 Closest Pair of Points in 2D using Divide and Conquer
Require: A list of points P in 2D plane, sorted by x-coordinate.
Ensure: The closest pair of points and their distance.
1: function ClosestPair(P )
2: n ← length of P
3: if n ≤ 3 then
4: return BruteForceClosestPair(P )
5: end if
6: mid ← n/2
7: Plef t ← P [1 . . . mid]
8: Pright ← P [mid + 1 . . . n]
9: dlef t ← ClosestPair(Plef t )
10: dright ← ClosestPair(Pright )
11: d ← min(dlef t , dright )
12: strip ← Points in P within distance d from the median x-coordinate
13: dstrip ← ClosestPairInStrip(strip, d)
14: return min(d, dstrip )
15: end function
16: function BruteForceClosestPair(P )
17: min dist ← ∞
18: for i ← 1 to length of P − 1 do
19: for j ← i + 1 to length of P do
20: dist ← Distance(P [i], P [j])
21: if dist < min dist then
22: min dist ← dist
23: end if
24: end for
25: end for
26: return min dist
27: end function
28: function ClosestPairInStrip(strip, d)
29: min dist ← d
30: Sort strip by y-coordinate
31: for i ← 1 to length of strip − 1 do
32: for j ← i + 1 to min(i + 7, length of strip) do
33: dist ← Distance(strip[i], strip[j])
34: if dist < min dist then
35: min dist ← dist
36: end if
37: end for
38: end for
39: return min dist
40: end function
41: function Distance(p1,
p p2)
42: return (p1.x − p2.x)2 + (p1.y − p2.y)2
43: end function
1
Algorithm 2 DSelect Algorithm
Require: An array A of length n and an integer i (1-based index).
Ensure: The i-th smallest element in A.
1: function DSelect(A, n, i)
2: if n == 1 then
3: return A[1]
4: end if
5: Split A into ⌈n/5⌉ groups of 5 elements each
6: Let C be an array of medians of each group
7: p ← DSelect(C, ⌈n/5⌉, ⌈⌈n/5⌉/2⌉) ▷ Find median of medians
8: Partition A into L (elements ≤ p) and R (elements > p)
9: Let j be the index of p in the partitioned array
10: if i == j then
11: return p
12: else if i < j then
13: return DSelect(L, j − 1, i)
14: else
15: return DSelect(R, n − j, i − j)
16: end if
17: end function