A common approach for such problems (especially if n is large) is to pre-compile the spatial index structure like kd tree or octtree and search for nearest neighbors using this helps. Through the octtree nodes, the available point is placed in the bunkers, so you can be sure that they are mutually close. You also minimize the number of comparisons.
Implementation sketch with an octet: you need a Node class that stores its bounding box. The resulting LeafNode class stores a small number of points to the maximum (for example, k = 20), which are added using the insert function. The derived NonLeafNode class stores links to 8 subnods (which can be either Leaf or NonLeafNodes).
The tree is represented by the root of the node, all insertions and queries begin here. The tree is created starting from the first k points inserted in the LeafNode. If k + 1st point is inserted, the bounding box is divided into 8 sub-boxes, and the points contained in it are sorted. The current LeafNode is replaced with one NonLeafNode with 8 subnodes. This is repeated until all points are in the tree.
To find the nearest neighbor, the tree moves, starting with the root Node, comparing it with the bounding box. If the request point is in the Node bounding box, the crawl is in node. Please note: if you find the nearest candidate, you also need to check with neighboring nodes in the octet.
To verify the implementation of kdtree, the wikipedia page looks rather complicated.
source share