I need an algorithm for the following problem:
I'm given a set of 2D points P = { (x_1, y_1), (x_2, y_2), ..., (x_n, y_n) } on a plane. I need to group them in pairs in the following manner:
- Find two closest points (x_a, y_a) and (x_b, y_b) in P.
- Add the pair <(x_a, y_a), (x_b, y_b)> to the set of results R.
- Remove <(x_a, y_a), (x_b, y_b)> from P.
- If initial set P is not empty, go to the step one.
- Return set of pairs R.
That naive algorithm is O(n^3), using faster algorithm for searching nearest neighbors it can be improved to O(n^2 logn). Could it be made any better?
And what if the points are not in the euclidean space?
An example (resulting groups are circled by red loops):