Skip to content

Instantly share code, notes, and snippets.

@loisgh
Last active February 1, 2018 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loisgh/0b7dbd5d31cae72706941edca3abd2ab to your computer and use it in GitHub Desktop.
Save loisgh/0b7dbd5d31cae72706941edca3abd2ab to your computer and use it in GitHub Desktop.
def binary_search(target_array, target, first, last):
#If the array is empty return -1
if not len(target_array):
return -1
#if the array has only one element in it, check that element.
elif len(target_array) == 1:
if target_array[0] == target:
return 0
else:
return -1
#If last is less than first you probably don't have a hit.
if last >= first:
mid = first + (last - first) / 2
if target_array[mid] == target:
return mid
elif target_array[mid] > target:
return binary_search(target_array, target, first, mid - 1)
else:
return binary_search(target_array, target, mid + 1, last)
else:
return -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment