The rank, select and access of the SD-array are correct full
This proof shows: correctness.
Let B have length n and its 1s at p0<⋯<pm−1, with m≥1, and let ℓ, Lo and H be the Elias-Fano code of this sequence with universe n. Write hj=⌊pj/2ℓ⌋, so pj=hj2ℓ+Lo[j]. We use two facts proved on the Elias-Fano page: the (j+1)-th 1 of H is at hj+j (fact A), and for 0≤h≤⌊(n−1)/2ℓ⌋, with P(h)=0 for h=0 and P(h)=SELECT0H(h)+1 otherwise, P(h)−h=∣{j:hj<h}∣ (fact B).
Select1 (line L1). By fact A, SELECT1H(j)−(j−1)=hj−1, so line L1 returns hj−12ℓ+Lo[j−1]=pj−1, the position of the j-th 1.
Rank1 (lines L2 to L7). If i=n, every 1 is before i and line L2 returns m. Let 0≤i<n, h=⌊i/2ℓ⌋ and l=imod2ℓ, so 0≤h≤⌊(n−1)/2ℓ⌋. Let J<={j:hj<h}, J=={j:hj=h} and J>={j:hj>h}. Since the hj are nondecreasing, these are consecutive ranges of indices in this order. By fact B with h, line L6 sets r=P(h)−h=∣J<∣. By fact B with h+1, P(h+1)−(h+1)=∣J<∣+∣J=∣, and line L5 sets s=P(h+1)−1−P(h)=∣J=∣. So the indices of bucket h are J=={r,…,r+s−1}. Fact B applies to h+1 when h+1≤⌊(n−1)/2ℓ⌋+1, which holds, because H has ⌊(n−1)/2ℓ⌋+1 zeros. Now:
- for j∈J<, pj<(hj+1)2ℓ≤h2ℓ≤i, so each such 1 is before i;
- for j∈J>, pj≥(h+1)2ℓ>i, so none is before i;
- for j∈J=, pj=h2ℓ+Lo[j]<h2ℓ+l=i if and only if Lo[j]<l.
So rank1(i)=r+∣{t<s:Lo[r+t]<l}∣, which line L7 returns. The positions in J= are strictly increasing with the same high part, so Lo[r],…,Lo[r+s−1] are strictly increasing, and the binary search for the first t with Lo[r+t]≥l computes this count.
Access (lines L8, L9). Let r=rank1(i), the number of 1s before i. If B[i]=1, then i=pr, so r<m and SELECT1(r+1)=pr=i. If B[i]=0, then either r=m, or the next 1 after the first r ones is pr>i, so SELECT1(r+1)=i. Line L9 returns B[i] in both cases.
Select0 (line L10). The function f(q)=(q+1)−rank1(q+1)=rank0(q+1) is nondecreasing in q and increases by one exactly at the positions q with B[q]=0. For 1≤j≤n−m, the least q with f(q)≥j is therefore the position of the j-th 0, and f(n−1)=n−m≥j ensures that it lies in [0,n−1], the range of the binary search.
The case m=0. Then ℓ=0, H has only zeros, every rank is 0 by fact B, and access returns 0 by line L9. ■