Last active
February 1, 2018 19:03
-
-
Save loisgh/0b7dbd5d31cae72706941edca3abd2ab to your computer and use it in GitHub Desktop.
This file contains 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(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