I am learning the algorithm now and have a question on the recursive approach to the binary search. I tried to code by myself as following:
def binary_search_rec(x, value):
x.sort()
length = len(x)
if length == 1 and x[0] == value:
return 0
elif length == 1 and x[0] != value:
return 'none'
else:
low = 0
high = length - 1
mid = (low + high)//2
if value == x[mid]:
return mid
elif value > x[mid]:
return mid + binary_search_rec(x[mid+1:], value)
else:
return binary_search_rec(x[0:mid], value)
The base case is an array with single element. However, I can't receive the correct result with the toy data:
binary_search_rec([1, 2, 3, 4], 3)
which will return 1.
Would you please help me figure out where I did wrong? Thank you in advance for your help.
return mid + 1 + binary_search_rec(x[mid+1:], value)