Files
pplus-library/mojo/local/binary-search.mojo
T
alexm 568474d52f
Test (in pplus-core) / in-core (push) Failing after 28m44s
Initial commit
2026-11-12 22:23:48 -05:00

25 lines
771 B
Mojo

# origin: Programming+ exercise binary-search
# status: unverified; `corpus.py verify` checks it on the pinned compiler
# probe: is x in the sorted list l? halve the range that could hold it each time
# expect-stdout: True
def contains_sorted(l: List[Int], x: Int) -> Bool:
# requires: forall k in [0, len(l) - 1) : l[k] <= l[k + 1]
var lo: Int = 0
var hi: Int = len(l)
while lo < hi:
# invariant: 0 <= lo <= hi <= len(l)
# decreases: hi - lo
var mid = (lo + hi) // 2
if l[mid] == x:
return True
elif l[mid] < x:
lo = mid + 1
else:
hi = mid
return False
def main():
var sorted_values: List[Int] = [2, 5, 8, 13, 21]
print(contains_sorted(sorted_values, 13))