Proofs: Brute-force nearest neighbor search
These are the human proofs of Brute-force nearest neighbor search, at full length.
The brute-force scan returns the k nearest points full
This proof shows: correctness.
Let be the points, the query and . For let , compared in lexicographic order. The indices are distinct, so the are distinct and totally ordered. For let be the set of the smallest elements of .
Invariant (H). At the start of the iteration of line L2 with index , and after the last iteration with , the heap holds exactly the elements of .
Initialization. Before the first iteration, , line L1 made empty, and .
Maintenance. Assume (H) at the start of iteration . Line L3 computes .
-
If , then , so and . Then is all of , since . Line L4 inserts , so .
-
Else and . Let be the largest element of , which is TOP by the max-heap property. Each element of is larger than .
- If , then is among the smallest of : at most elements of are below it, and no other element is. The element now has smaller elements ( and ), so it leaves. So , which is what line L5 makes.
- If , then the elements of are smaller than , so and . Line L5 does nothing.
The case cannot occur, because the elements are distinct.
In each case (H) holds at the start of iteration .
Termination. The loop runs for , so it stops after iterations, with .
Theorem. Line L6 returns a list of pairs, and the set of their points is a correct answer to the -nearest neighbor query: for each and .
Proof. By (H), line L6 sorts , which has elements. Let and , with pairs and . Since and is the set of the smallest elements, . The first component of a pair is the distance, so lexicographic order gives .
Ties. When several points have the distance of the -th result, takes those with the smallest indices, because the second component decides between pairs of equal distance.