We present a language-agnostic range algebra that derives correct index intervals for splitting arrays and implementing binary search, eliminating off-by-one and empty-range bugs. From two primitives -- $\lfloor n/2\rfloor$ and $\lceil n/2\rceil = \lfloor (n + 1)/2\rfloor$ -- we obtain four canonical splits (Natural, Left+, Right+, Center-cut) with proofs of coverage and balance for all $n \ge 0$ and any base index $b \in \mathbb{Z}$. We record invariants (normalization to left-closed/right-open intervals $[u, w)$ with len $= w - u$), document cross-language division quirks, and give drop-in code patterns and property tests. The result is a small, memorable spec that can be copied verbatim into C/C++/Java/C\#/Go/Rust/Swift/JS/Python.
翻译:我们提出了一种与语言无关的范围代数,用于推导分割数组和实现二分查找的正确索引区间,从而消除差一错误和空范围错误。从两个基本操作——$\lfloor n/2\rfloor$ 和 $\lceil n/2\rceil = \lfloor (n + 1)/2\rfloor$——出发,我们推导出四种规范分割方式(自然分割、左偏分割、右偏分割、中心切割),并证明了对于所有 $n \ge 0$ 及任意基索引 $b \in \mathbb{Z}$ 的覆盖性和平衡性。我们记录了不变性(归一化为左闭右开区间 $[u, w)$,其长度 $= w - u$),整理了跨语言除法运算的特性差异,并提供了可直接使用的代码模式和属性测试。最终成果是一个简洁易记的规范,可直接复制到 C/C++/Java/C\#/Go/Rust/Swift/JS/Python 等语言中使用。