Created
December 17, 2014 15:56
-
-
Save avenet/2a7e0dd43e60753c6984 to your computer and use it in GitHub Desktop.
Binary search implementation
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 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