Files
pplus-web/tests/snapshots/sync-mojo/binary-search.mojo
T
2026-10-05 03:03:38 +00:00

26 lines
698 B
Mojo

# Generated by Programming+ from pseudo. Not reviewed for Mojo best practices.
# Is X in the sorted list L? Halve the range that could hold it each time.
def contains_sorted(l: List[Int], x: Int) -> Bool:
# REQUIRE FORALL K IN [0, LENGTH(L) - 1) : L[K] <= L[K + 1]
var lo: Int
var hi: Int
var mid: Int
lo = 0
hi = len(l)
# INVARIANT 0 <= Lo AND Lo <= Hi AND Hi <= LENGTH(L)
# DECREASES Hi - Lo
while lo < hi:
mid = (lo + hi) // 2
if l[mid] == x:
return True
elif l[mid] < x:
lo = mid + 1
else:
hi = mid
return False
def main():
print(contains_sorted(List[Int](2, 5, 8, 13, 21), 13))