I am implementing binary search in Python, I created a function for it but somehow, I am kinda stuck in between. My funtion returns "None" as the output and I can't figure out why it is doing that. My code here:
x = [1,2,3,4,5,6,7,8,9,10]
y = 9
def bin_search(s_list, key):
print(s_list)
m = s_list[len(s_list)//2]
if m == key:
return 1
elif m < key:
bin_search(s_list[s_list.index(m)+1:],key)
else:
bin_search(s_list[0:s_list.index(m)],key)
print( bin_search(x, y)) It gives, the folowing output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[7, 8, 9, 10]
None
When you make the recursive calls make sure to return
the values so they're passed up the stack to the caller. Just writing bin_search(...)
ignores the return value.
if m == key:
return 1
elif m < key:
return bin_search(s_list[s_list.index(m)+1:],key)
else:
return bin_search(s_list[0:s_list.index(m)],key)