Verified word-RAM routine: binary search finds the first entry ≥ key in 8·size(n) + 2 steps
ProvedCentralStrQ.bsearch_specdata-structureshoare-logicverified-programmingword-ram
Setting. Let for be a sorted array of words. Assume the hypotheses BSearchHyp:
- the registers are distinct, and distinct from the input cells and from the array cells;
- and ;
- there is no overflow: ;
- bounds every address used.
The search starts with , and space usage .
Conclusion. The structured program bsearchStmt reaches its end within
steps. The final value satisfies , for all , and for all . So is the number of entries smaller than , which is the lower bound used by predecessor search. Only the four registers change, and the space usage stays at most .
This is a word-RAM routine with a verified worst-case running time, the kind of building block behind query bounds.
Preamble
import Mathlib import Definitions.Def_CentralStrQ_Machine import Definitions.Def_CentralStrQ_Hoare import Definitions.Def_CentralStrQ_Structured set_option autoImplicit false
Formal statement
namespace CentralStrQ
open WordRAM
/-- **Binary search in `O(log n)` steps.** On a sorted array of `n` words at `base`
(`BSearchHyp`), started with `[lo] = 0` and `[hi] = n`, `bsearchStmt` ends within
`8·⌈log₂(n + 1)⌉ + 2` steps (`Nat.size n` bits) with `[lo]` the number of entries `< key`
(every entry before `[lo]` is `< key`, every entry from `[lo]` on is `≥ key`), changing only the
four registers and with space usage at most `R`. -/
theorem bsearch_spec {w : Width} {lo hi mid ptr baseC keyC base n key R r₀ : ℕ} {m₀ : Memory w}
(h : BSearchHyp lo hi mid ptr baseC keyC base n key R m₀)
(hlo : (m₀ lo).toNat = 0) (hhi : (m₀ hi).toNat = n) (hr₀ : r₀ ≤ R) :
STriple (bsearchStmt lo hi mid ptr baseC keyC) (fun m r => m = m₀ ∧ r = r₀)
(fun m r => (m lo).toNat ≤ n ∧ (∀ j < (m lo).toNat, (m₀ (base + j)).toNat < key) ∧
(∀ j, (m lo).toNat ≤ j → j < n → key ≤ (m₀ (base + j)).toNat) ∧
(∀ a, a ≠ lo → a ≠ hi → a ≠ mid → a ≠ ptr → m a = m₀ a) ∧ r ≤ R)
(Nat.size n * 8 + 2) := by sorry
end CentralStrQ
Source
Structured-programming layer (Hoare 1969; R. W. Floyd, Assigning meanings to programs, 1967) for the published Hoare-triple infrastructure Def_CentralStrQ_Hoare. Infrastructure for the published deterministic word RAM Def_CentralStrQ_Machine (Kempa, Kociumaka, A Complete Characterization of Central String Queries in Compact Space, STOC 2027 submission, Section 3.2, p. 13; T. Hagerup, Sorting and searching on the word RAM, STACS 1998, https://doi.org/10.1007/BFb0028575). Hoare-style rules after C. A. R. Hoare, An axiomatic basis for computer programming, Commun. ACM 12(10), 1969, https://doi.org/10.1145/363235.363259.