25 lines
771 B
Mojo
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))
|