Skip to content

Instantly share code, notes, and snippets.

@raol
Last active December 24, 2015 21:38
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 raol/6866479 to your computer and use it in GitHub Desktop.
Save raol/6866479 to your computer and use it in GitHub Desktop.
Binary search sample
def binarysesarch(x, a):
""" binarysesarch implementation
>>> binarysesarch(1, [1])
0
>>> binarysesarch(1, [])
-1
>>> binarysesarch(2, [1])
-1
>>> binarysesarch(1, [0, 1, 1, 2])
1
>>> binarysesarch(2, [0, 1, 2, 2])
2
>>> binarysesarch(2, [0, 1, 2])
2
>>> binarysesarch(0, [0, 0, 1, 2])
0
"""
lo = 0
hi = len(a)
while lo < hi:
mid = lo + (hi - lo)//2
if x > a[mid]:
lo = mid + 1
elif x < a[mid]:
hi = mid
elif mid > 0 and a[mid - 1] == x:
hi = mid
else:
return mid
return -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment