Created
September 3, 2021 03:21
-
-
Save harendra21/64f2831f11f005f07789bd3f3261bb09 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_recursive(list_of_numbers, number, start=0, end=None): | |
# The end of our search is initialized to None. First we set the end to the length of the sequence. | |
if end is None: | |
end = len(list_of_numbers) - 1 | |
if start > end: | |
# This will happen if the list is empty of the number is not found in the list. | |
raise ValueError('Number not in list') | |
mid = (start + end) // 2 # This is the mid value of our binary search. | |
if number == list_of_numbers[mid]: | |
# We have found the number in our list. Let's return the index. | |
return mid | |
if number < list_of_numbers[mid]: | |
# Number lies in the lower half. So we call the function again changing the end value to 'mid - 1' Here we are entering the recursive mode. | |
return binary_search_recursive(list_of_numbers, number, start, mid - 1) | |
# number > list_of_numbers[mid] | |
# Number lies in the upper half. So we call the function again changing the start value to 'mid + 1' Here we are entering the recursive mode. | |
return binary_search_recursive(list_of_numbers, number, mid + 1, end) | |
print binary_search_recursive([1,2,3,5,8],6) | |
print binary_search_recursive([1,2,3,5,8],5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment