Sie sind auf Seite 1von 18

Closest-Pair Algorithm

Given: A set of points in 2-D

Closest-Pair Algorithm
Step 1: Sort the points in one D

Closest-Pair Algorithm
Lets sort based on the X-axis
O(n log n)
4
9

3
1

1
3

1
0

1
1
1
2

1
4

Closest-Pair Algorithm
Step 2: Split the points, i.e.,
Draw a line at the mid-point between 7 and
8
4
9

3
1

1
3

Sub-Problem
1

1
0

1
1

1
2
Sub-Problem
2

1
4

Closest-Pair Algorithm
Advantage: Normally, wed have to
compare each of the 14 points with every
other point.
(n-1)n/2 = 13*14/2 = 91 comparisons
4
9

3
1

1
3

Sub-Problem
1

1
0

1
1

1
2
Sub-Problem
2

1
4

Closest-Pair Algorithm
Advantage: Now, we have two subproblems of half the size. Thus, we have to
do 6*7/2 comparisons twice, which is 42
comparisons
solution d = min(d1, d2)

4
9
2

d1

d2
7

3
5

Sub-Problem
1

1
3

1
0

1
1

1
2
Sub-Problem
2

1
4

Closest-Pair Algorithm
Advantage: With just one split we cut the
number of comparisons in half. Obviously,
we gain an even greater advantage if we
split the sub-problems.
d = min(d1, d2)

4
9
2

d1

d2
7

3
5

Sub-Problem
1

1
3

1
0

1
1

1
2
Sub-Problem
2

1
4

Closest-Pair Algorithm
Problem: However, what if the closest two
points are each from different subproblems?

4
9
2

d1

d2
7

3
5

Sub-Problem
1

1
3

1
0

1
1

1
2
Sub-Problem
2

1
4

Closest-Pair Algorithm
Here is an example where we have to
compare points from sub-problem 1 to the
points in sub-problem 2.

d1

Sub-Problem
1

d2

9
7

1
3

1
0

1
1

1
2
Sub-Problem
2

1
4

Closest-Pair Algorithm
However, we only have to compare points
inside the following strip.
d = min(d1, d2)
4

d1

3
1

Sub-Problem
1

1
3

d2
1
0

1
1

1
2
Sub-Problem
2

1
4

Closest Pair D & C


Algorithm

1)We sort all points according to x coordinates.


2)Divide all points in two halves.
3)Recursively find the smallest distances in both subarrays.
4)Take the minimum of two smallest distances. Let the
minimum be d.
5)Create an array strip[] that stores all points which are at
most d distance away from the middle line dividing the two
sets.
6)Find the smallest distance in strip[].
7)Return the minimum of d and the smallest distance
calculated in above step 6

Closest-Pair Algorithm
Step 3: But, we can continue the
advantage by splitting the sub-problems.

4
9

3
1

1
3

1
0

1
1
1
2

1
4

Closest-Pair Algorithm
Step 3: In fact we can continue to split until
each sub-problem is trivial, i.e., takes one
comparison.

4
9

3
1

1
3

1
0

1
1
1
2

1
4

Closest-Pair Algorithm
Finally: The solution to each sub-problem is
combined until the final solution is
obtained

4
9

3
1

1
3

1
0

1
1
1
2

1
4

Closest-Pair Algorithm
Finally: On the last step the strip will likely
be very small. Thus, combining the two
largest sub-problems wont require much
work.
4
9

3
1

1
3

1
0

1
1
1
2

1
4

Das könnte Ihnen auch gefallen