Proofs: Binary search symbol table
These are the human proofs of Binary search symbol table, at full length.
RANK counts the smaller keys, and PUT and DELETE keep the arrays sorted full
This proof shows: correctness.
Invariant (I). , and the table holds exactly the pairs for .
For a key , let . Under (I), the keys less than are exactly , and if is in the table, it is .
Lemma (RANK). Under (I), RANK returns after at most passes of the loop.
Proof. We use the loop invariant
(R) , every key in is less than , and every key in is greater than .
Line L1 sets and ; both ranges are empty and (R) holds. In a pass, , and line L3 gives . If , then since the keys increase, every key in is greater than , and line L4 sets ; (R) holds. If , every key in is less than , and line L5 sets ; (R) holds. Otherwise , and line L6 returns ; since the keys increase strictly, exactly the keys before it are less than , so .
If the loop ends, , and with (R), . Then the two ranges of (R) cover all indices, so exactly keys are less than , and line L7 returns .
Passes. Let be the size of the range. Line L3 splits it into cells to the left of and to the right. Either way the new size is at most . Starting from , after passes , which is 0 for . So there are at most passes.
GET. By the lemma, line L8 finds . If is in the table, it is , and line L8 returns its value by (I). If it is not, then either or , and line L8 returns NIL. Nothing is written.
PUT. Let from line L9. If and , line L10 replaces the value of and changes no key, so (I) holds for the table with in place of the old pair of . Otherwise is not in the table, and . The loop of line L11 runs . At step it copies cell to cell . Cell is either the free cell (for ) or a cell already copied at step ; cell is not yet written. So after the loop, $keys[j] $ holds the old for , and cells are unchanged; the same holds for . Line L12 writes at index and sets the count to . The new key sequence is $keys[0..i-1], k, $ old , which is strictly increasing, and the pairs are the old pairs and . So (I) holds.
DELETE. Let . If is not in the table, line L13 returns and nothing changes. Otherwise . The loop of line L14 runs and copies cell to cell . Cell has not yet been written by the loop, so after it, cell holds the old cell for . Line L15 sets the count to . The new key sequence is the old one without , which is still strictly increasing, and the pairs are the old pairs without the pair of . So (I) holds.
Order operations. Under (I), is the least key, the greatest, and has exactly smaller keys, so it is select. For ceiling, is the least key , since all earlier keys are less than . For floor, if it is the answer; otherwise every key is greater than , and the largest key less than is . The keys in are those with index from to , plus if it equals ; their count is , plus 1 in that case.