Consider the following non-recursive solution of binary search that finds and returns the
position of the key in alist, or returns 'Item is not in the list' if key is not in the list:
def binary_search1(key, alist, low, high):
# finds and returns the position of key in alist
# or returns 'Item is not in the list'
# - key is the target integer that we are looking for
# - alist is a list of valid integers that is searched
# - low is the lowest index of alist
# - high is the highest index of alist
found = False
while (not found and low <= high):
guess = (high + low) // 2
if (key == alist[guess]):
found = True
else:
if (key < alist[guess]):
high = guess - 1
else:
low = guess + 1
if (not found):
guess = 'Item is not in the list'
return guess
Sample calls to binary_search1:
def main():
some_list = [-8, -2, 1, 3, 5, 7, 9]
print(binary_search1(9, some_list, 0, len(some_list) - 1))
print(binary_search1(-8, some_list, 0, len(some_list) - 1))
print(binary_search1(4, some_list, 0, len(some_list) - 1))
main()
Sample Output:
6
0
Item is not in the list
Your task is to write a recursive binary search function called binary_search2 that will do the
same task that is done by binary_search1 i.e. if binary_search1 in the above sample calls is
replaced with binary_search2, it would produce the same output. The parameters for
binary_search2 must be same as binary_search1.
NOTES:
1) You can assume that the key will always be an integer number.
2) You can assume that alist only contains integers.