Skip to content

Instantly share code, notes, and snippets.

@avenet
Created December 17, 2014 15:56
Show Gist options
  • Save avenet/2a7e0dd43e60753c6984 to your computer and use it in GitHub Desktop.
Save avenet/2a7e0dd43e60753c6984 to your computer and use it in GitHub Desktop.
Binary search implementation
def binary_search(array, value):
return _binary_search(array, value, 0, len(array)-1)
def _binary_search(array, value, i, j):
if i > j:
return -1
middle = (i+j)/2
if array[middle] == value:
return middle
elif array[middle] > value:
return _binary_search(array, value, i, middle)
return _binary_search(array, value, middle+1, j)
print binary_search(range(19), 100)
print binary_search(range(10), 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment