Uniform binary search returns the first index of x, or NIL, with exactly floor(lg n) + 1 order comparisons full
This proof shows: correctness, termination, complexity.
Let A[0…n−1] be sorted in non-decreasing order, n≥0, and let x be a key. For the argument only, extend A with A[−1]=−∞ and A[n]=+∞. Let ℓ=∣{j:0≤j<n, A[j]<x}∣ be the lower bound of x. Since A is sorted, A[j]<x for −1≤j<ℓ and A[j]≥x for ℓ≤j≤n. We prove that UNIFORM-BINARY-SEARCH(A,x) returns ℓ when ℓ<n and A[ℓ]=x, and NIL otherwise, that it reads only cells A[0],…,A[n−1], and that it makes exactly ⌊lgn⌋+1 order comparisons when n≥1.
If n=0, line L1 returns NIL, which is correct. Assume n≥1. Line L2 sets p=2k with k=⌊lgn⌋, so p≤n<2p. Line L4 reads A[p−1], a real cell since 1≤p≤n.
Invariant. Before each test of line L6:
- s is a power of 2 with 1≤s≤p.
- −1≤b and b+s≤n.
- A[b]<x≤A[b+s], that is, b<ℓ≤b+s.
Start. Line L5 sets s=p, so statement 1 holds. There are two cases for line L4.
- If A[p−1]≥x, then b=−1, and b+s=p−1≤n−1. Also A[−1]=−∞<x≤A[p−1].
- If A[p−1]<x, then b=n−p. From n<2p we get b≤p−1, so A[b]≤A[p−1]<x, and b≥0. Also b+s=n and x≤A[n]=+∞.
Step. A pass runs only when s>1, so s≥2 and s′=s/2 is a power of 2 with 1≤s′<s. The pass reads A[b+s′]. Since b≥−1 and s′≥1, the index is at least 0; since b+s≤n and s′<s, it is at most n−1. So it is a real cell.
- If A[b+s′]<x, the new value is b′=b+s′. Then A[b′]<x, and b′+s′=b+s, so b′+s′≤n and x≤A[b′+s′].
- Otherwise b′=b, A[b]<x, and x≤A[b+s′], with b+s′<b+s≤n.
In both cases the three statements hold for (b′,s′).
Termination and the count. Each pass halves s, which starts at p=2k, so the loop makes exactly k passes and stops with s=1. Each pass makes one order comparison, and line L4 makes one, so the total is k+1=⌊lgn⌋+1 for every key.
The result. At the end s=1, and statement 3 gives b<ℓ≤b+1, so ℓ=b+1. If b+1<n and A[b+1]=x, line L9 returns ℓ; since every index j<ℓ has A[j]<x, this is the smallest index of x. Otherwise, either ℓ=n, so every item is <x, or A[ℓ]>x, so every item from ℓ on is >x and every item before is <x. In both cases x is not in A, and line L10 returns NIL, which is correct. ■