Search code examples
c#algorithmbrute-forcedivide-and-conquer

shortest distance in a series of xy coordinates


I have an assignment which compares 2 different algorithms for a problem. Here's the problem:

Suppose I have a series of xy coords like this :

A(2,3), B(5,6), C(7,8), D(6,2), E(5,5), etc..

And I want to find 2 coords which have the shortest distance between them. One of the solution is using brute force (matching them one by one), but there is another solution using "divide and conquer" method..

Can you help me with the "divide and conquer" method?


Solution

  • The recursive divide-and-conquer approach works as follows:

    1) Sort points according to their x-coordinates.
    2) Split the set of points into two equal-sized subsets by a vertical line x=xmid.

    3) Solve the problem recursively in the left and right subsets. This
    yields the left-side and right-side minimum distances dLmin and dRmin, respectively.

    4) Find the minimal distance dLRmin among the pair of points in which one point lies on the left of the dividing vertical and the second point lies to the right.

    5) The final answer is the minimum among dLmin, dRmin, and dLRmin. (source)

    It has a complexity of O(n log n). There is also a pseudocode implementation here and a visual description of the method here.