Created
June 22, 2017 09:22
-
-
Save isurum/98c2ecde2d831c45177037a499de6ede to your computer and use it in GitHub Desktop.
Binary Search implementation using Python.
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 search(arr, x, lowest_index, highest_index): | |
#find the middle index | |
middle_index = lowest_index + (highest_index - lowest_index) / 2 | |
print "Middle index is ", middle_index | |
# checks whether the value is in the middle index | |
if (arr[middle_index] == x): | |
return middle_index | |
elif (arr[middle_index] > x): | |
# checks in <- direction | |
return search(arr, x, lowest_index, highest_index - 1) | |
else: | |
# checks in -> direction | |
return search(arr, x, middle_index + 1, highest_index) | |
# array to pass as variable | |
arr = [1, 3, 5, 7, 9, 11, 15, 17, 19] | |
# result of the search | |
index = search(arr, 3, 0, len(arr)) | |
#checks whether result is -1 or other integer value | |
if index != -1: | |
print "Element is present at", index | |
else: | |
print "Your searched item is not in the array" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment