Square trees
A square tree occupies a square of space and divides it into four children and a half sizes along the X and Y axis.
+---+---+ | | | Each square is a child | | | of the parent; when you +---+---+ get to leaves a node has | | | a single point or a list | | | of points. +---+---+
This data structure is recursive and you look for points by checking which child holds the point until you hit the sheet. The sheet either has one member (a point with coordinates X, Y), or a list of members, depending on the implementation. If you fill in the node, you divide it by 4 and give it to the children. In fact, the data structure is a generalization of the binary tree, so it is not necessarily balanced.
Balancing a quad tree may not be necessary for your purposes and is left as an exercise for the reader - try to find a "balanced quad tree" on the Internet
Note that this data structure cannot index elements that may overlap, but if you only save points, this will not be a problem.
Search for nearest neighbors in a square tree
Above my head, here's a quick and dirty algorithm for finding the closest neighbors "n" to your point. This is not necessarily optimally effective, but it will be quite simple to implement. If anyone has a link to the best, feel free to post it in the comments or responses.
Find the square node tree containing your item, keeping a list of your parents.
Click all the points in the node in the priority queue based on their distance from your base point (i.e., according to the length of the hypotenuse according to the Pythagorean theorem). depending on the implementation, there may be one or more per node. For a simple implementation of the priority queue, the data structure is a binary heap search.
If any of the "n" points is farther, then add the contents of its neighbors to the edges of the bounding box. those. if your base point is close to the edge of the bounding box, it is possible that neighboring nodes in the tree may contain points that are closer than the points found in your bounding box. To do this, you need to back up the tree, so you need to keep track of your parent nodes.
When all the "nearest" points are closer to the edges of your bounding box, you know that there could not be neighbors that you missed. Therefore, the "n" nearest points in this field should be your "n" nearest neighbors.
ConcernedOfTunbridgeWells
source share