Proofs: Spatial hashing
These are the human proofs of Spatial hashing, at full length.
Spatial hashing keeps one entry per box and cell, and a query reports each box that meets it exactly once full
This proof shows: correctness, termination.
Write for the set of cells that the closed box meets, and for the cell of the point . For a closed box , a cell is in exactly when and ; this is the set of cells of the points of , since the cell index is a monotone function of each coordinate and takes every integer value between its values at the two ends. In particular, if then .
Invariant (S). For each stored box and each , bucket holds the entry exactly once, and there are no other entries.
INSERT. Lines L1 and L2 add the entry to bucket for each and for no other cell. If was not stored before, this gives (S) for the new set. is finite, so INSERT stops.
DELETE. By (S), for each the bucket holds the entry once, and line L9 removes it; moving the last entry of the list into the free place does not change the multiset of the other entries. After the loop, no entry of is left and the others are kept, so (S) holds for the set without . If the box was not stored, no entry matches, and nothing changes.
QUERY. Soundness. An id is reported in line L7 only for an entry that passed line L6, so meets , and by (S) is stored.
Each stored box that meets is reported. Let be stored with . The intersection of two closed boxes that meet is the closed box , so its lower left corner lies in both and . Let . Since , , and line L4 visits it. Since , , and by (S) bucket holds . Line L5 meets this entry, line L6 lets it pass, and the test of line L7 holds, so is reported.
Each is reported once. Line L4 visits each cell of once. In a visited cell , by (S) bucket holds at most one entry for the box, so the box can be reported at most once per cell, and only when . The point has exactly one cell, so the box is reported in at most one cell.
Termination. is finite and each bucket is a finite list.
CLOSE PAIRS. For each cell, the code tests each pair of distinct entries of that cell, and reports the pair when the boxes meet and the lower left corner of their intersection lies in the cell. The argument above, with in place of and in place of , shows that each pair of stored boxes that meet has both entries in the cell of that corner, and that the corner has one cell, so each such pair is reported exactly once, and no other pair is reported.