Last active
December 24, 2015 21:38
-
-
Save raol/6866479 to your computer and use it in GitHub Desktop.
Binary search sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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