Proofs: Bit vector
These are the human proofs of Bit vector, at full length.
The packed bit vector answers access, rank and select correctly full
This proof shows: correctness.
We use the pseudocode of the page, with words of bits, and write for bit of a word . Let be the input and the number of its 1s.
Lemma 1 (BUILD). After BUILD, (P1) for , and (P2) for each with .
Proof. The map is one to one, so each bit of each word belongs to at most one position . Line L1 sets each word to 0. Line L3, at step , sets the bit to 1 when , and the OR leaves all other bits as they are. So after the loop of line L2, the bit of position is 1 exactly when , which is (P1). The bits that belong to no position were set to 0 by line L1 and never written, which is (P2).
The structure is static, so (P1) and (P2) hold for each later query.
Lemma 2 (ACCESS). ACCESS returns for .
Proof. For a word and , . With and , line L4 returns by (P1).
Lemma 3 (RANK1). RANK1 returns for .
Proof. Let and , so . The set is the disjoint union of the blocks for and of . Each block lies inside because . By (P1), the number of 1s of in block is the number of 1 bits of , which line L6 adds. If , then , so exists. The word keeps the bits to of , which by (P1) are , and line L7 adds their number of 1s. If , the last part is empty and line L7 adds nothing. So line L8 returns the number of 1s in .
Lemma 4 (SELECT1). For , SELECT1 returns the position with and .
Proof. Let be the argument and the number of 1 bits of . By (P1) and (P2), is the number of 1s of in block , and . We use this invariant of the loop of line L10:
(S) and .
It holds at the start with and . An iteration runs only if , and it sets and , so (S) holds again. The loop stops: if it reached , then (S) would give , against . So the loop stops at a word with , and grows by one in each iteration, so at most iterations run. By (S), exactly ones of lie before block , so the wanted 1 is the -th 1 of , counted from the least significant bit.
For , the word is with its lowest 1 bit cleared: if the lowest 1 is at bit , then has bits to set, bit cleared and the higher bits of , so the AND keeps the higher bits and clears bits to . Line L12 does this times on , which has ones, so it removes the lowest ones and after it. The lowest 1 of the new is the -th 1 of , at bit $t = $ LOWEST. Line L13 returns . By (P1) , and the 1s before are the ones before block and the ones of below bit , so .
Lemma 5 (rank and select of 0s). , and SELECT0 is correct when it runs SELECT1 on the words , with the last word masked to its first bits.
Proof. Each position holds a 0 or a 1, so the two counts add to . For select, the masked complemented words satisfy (P1) and (P2) for the bit sequence : the complement flips each bit, and the mask clears exactly the padding bits, which the complement had set. Lemma 4 applied to that sequence gives the position of the -th 0 of .