ClosestPair

Closest Pair is an algorithm that finds the closest pair of a given array of points By utilizing the Divide and Conquer methodology of solving problems so that it reaches the correct solution with O(nlogn) complexity.

Given points and we're required to find the two red ones

As we see in the above image there are an array of points and we need to find the closest two, But how do we do that without having to compare each two points which results in a whopping O(n^2) complexity?

Here is the main algorithm (Steps) we'll follow.

var innerPoints = mergeSort(points, sortAccording : true)
let line:Double = (p[mid].x + p[mid+1].x)/2

and just recursively calls itself until it reaches the base case we don't detect those points.

 Points lying near the division line

var strip = [Point]()   
var i=0, j = 0
while i<n
{
	if abs(p[i].x - line) < min
	{
		strip.append(p[i])
		j+=1
	}
	i+=1
}

The strip with 4 points shown

while i<j
    {
        x = i+1
        while x < j
        {
            if (abs(strip[x].y - strip[i].y)) > min { break }
            if dist(strip[i], strip[x]) < temp
            {
                temp = dist(strip[i], strip[x])
                tempFirst = strip[i]
                tempSecond = strip[x]
            }
            x+=1
        }
        i+=1
    }

So this is the rundown of how the algorithm works and you could see the fun little math tricks used to optimize this and we end up with O(nlogn) complexity mainly because of the sorting.

See also

See the playground to play around with the implementation of the algorithm

Wikipedia

Written for Swift Algorithm Club by Ahmed Nader