0

I have a list of points in cartesian plane, and a test point. I want to find list indices of three points nearest to test point. What's the better way to find these indices? Thanks in advance for tour replies.

=== EDIT ===

I've found a solution in C++. At first I create a vector:

typedef struct
{
  int iIndex;
  double dSqrDistance;
} IndexedDistance;

std::vector<IndexedDistance> xDistanceVector;

and then a function to sort its elements

bool compareIndexedDistance(IndexedDistance xD1, IndexedDistance xD2)
{
  return (xD1.dSqrDistance < xD2.dSqrDistance);
}

Then in a loop I calculate all distances, then I sort them and at the end I take first three elements:

IndexedDistance xDistanceElement;
for (int i = 0; i < xPointList.size(); i++)
{
  dSqrDistance = xPointList.at(i).sqrDistance(xTestPoint);
  xDistanceElement.iIndex = i;
  xDistanceElement.dSqrDistance = dSqrDistance;
  xDistanceVector.push_back(xDistanceElement);
}

std::sort(xDistanceVector.begin(), xDistanceVector.end(), compareIndexedDistance);
xDistanceVector.resize(3);

In this way, I found what I need. I don't know if it's the best way, but it seems to work.

Jepessen
  • 11,744
  • 14
  • 82
  • 149

1 Answers1

0

Binary space partitioning may provide algorithms complexity of O(log n * log n).

  1. Determine bounds of your point set. Infinum and supremum points will give you an axis-aligned square containing all the points in set.
  2. Split the bounding square in two by any of axis. Make a separate list of contained points for each square. Link each of bounding squares to the parent square.
  3. Repeat splitting bounding squares (step 2) until corresponding lists of containing points will be reasonably small to utilize exhaustive search.

Now you will be able to use tree search to localize space around your point of interest and therefore greatly reduce number of distance tests.

The tricky part is that you must scan all the neighbour bounding squares around the point of interest because the closest point may lie in any of them.