I am in an intro to CS class and was given the assignment to perform a recursive binary search that returns the index of the searched item, should it be present in the list, otherwise it should return negative one.
The code that class the function is as follows: (python code)
numList = [1,2,3,4,5,...6,7,8,9]
key = <insert number to search for here>
position = binarySearch(numList, key)
print("Your number is at " + str(position))
I am not allowed to modify the arguments of the function.
given
def binarySearch(numList, key):
<code here>
Any tips on how to accomplish this? I always seem to be unable to recover the index of the original number. The binary search must be recursive.
copied binary search from geeksforgeeks
implement the code according to the problem statement
numList = [1,2,3,4,5,6,7,8,9]
key = 6
def binarySearch(numList, key):
def binary_search(alist, start, end, key):
"""Search key in alist[start... end - 1]."""
if not start < end:
return -1
mid = (start + end)//2
if alist[mid] < key:
return binary_search(alist, mid + 1, end, key)
elif alist[mid] > key:
return binary_search(alist, start, mid, key)
else:
return mid
return binary_search(numList, 0, len(numList), key)
print(binarySearch(numList, key)) # otput 5, index start from 0