I was trying to write binary search in python. What i write is :
arr = [6, 13, 14, 25, 33, 43, 51, 53, 64, 72, 84, 93, 95, 96, 97]
def binarySearch(arr, low, high, key):
if(low <= high):
mid = (low + high) // 2
if(arr[mid] == key):
return key
elif(arr[mid] > key):
binarySearch(arr, low, mid - 1, key)
else:
binarySearch(arr, mid + 1, high, key)
else:
return -1
i = binarySearch(arr, 0, len(arr) - 1, 33)
print(i)
It returns None. Then i discovered that i did not put return statements at the beginning of recursive calls. But in my head, without return statements, it should return the key anyway, because first it controls if it matches with key. Why function keep executing after finding the key and returns None instead of key.