Skip to content

Instantly share code, notes, and snippets.

@kunishi
Created June 11, 2022 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kunishi/a7e1240308711c4c173cf3078fbe86a1 to your computer and use it in GitHub Desktop.
Save kunishi/a7e1240308711c4c173cf3078fbe86a1 to your computer and use it in GitHub Desktop.
def binsearch(l, x):
f, t = 0, len(l) - 1
j = (f + t) // 2
while f <= t:
j = (f + t) // 2
if l[j] == x:
break
elif l[j] < x:
f = j + 1
else:
t = j - 1
if l[j] < x:
return l[:j+1], l[j+1:]
else:
return l[:j], l[j:]
if __name__ == '__main__':
l = [1, 2, 4, 6, 7, 10, 12]
for key, smaller, larger in [
[4, [1, 2], [4, 6, 7, 10, 12]],
[8, [1, 2, 4, 6, 7], [10, 12]]
]:
l1, l2 = binsearch(l, key)
assert (l1, l2) == (smaller, larger), f'{(l1, l2)}, {(smaller, larger)}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment