Skip to content

Instantly share code, notes, and snippets.

@martinusso
Last active September 27, 2015 10:58
Show Gist options
  • Save martinusso/1259292 to your computer and use it in GitHub Desktop.
Save martinusso/1259292 to your computer and use it in GitHub Desktop.
Recursive binary search in Python
def get_index_recursive(vector, number, index = -1, prior_index = 0):
index_helper = index if index > -1 else int(len(vector)/2)
if vector[index_helper] < number:
prior_index_helper = prior_index if prior_index > 0 else len(vector)
index_helper = int((prior_index_helper - index_helper)/2) + index_helper
elif vector[index_helper] > number:
prior_index_helper = index_helper +1
index_helper = int(index_helper/2)
else:
return index_helper
return get_index_recursive(vector, number, index_helper, prior_index_helper)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment