Skip to content

Instantly share code, notes, and snippets.

@rasoolims
Created October 6, 2016 23:53
Show Gist options
  • Save rasoolims/27774c127dec2607fa07e465cff38e16 to your computer and use it in GitHub Desktop.
Save rasoolims/27774c127dec2607fa07e465cff38e16 to your computer and use it in GitHub Desktop.
binary search
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