Created
October 6, 2016 23:53
-
-
Save rasoolims/27774c127dec2607fa07e465cff38e16 to your computer and use it in GitHub Desktop.
binary search
This file contains 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
arr = [1,2,3,4,5,6,8,9,10,12,13,15] | |
def binary_search(a, v): | |
s = 0 | |
e = len(a) - 1 | |
mid = (s+e)/2 | |
while s <= e: | |
if a[mid] == v: | |
return mid | |
elif a[mid] < v: | |
s = mid + 1 | |
mid = (s+e)/2 | |
elif a[mid] > v: | |
e = mid - 1 | |
mid = (s+e)/2 | |
return -1 | |
print binary_search(arr, 9) | |
print binary_search(arr, 0) | |
print binary_search(arr, 16) | |
print binary_search(arr, 15) | |
print binary_search(arr, 1) | |
print binary_search(arr, 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment