I am trying to implement Binary Search in Python with recursion.
I write code above:
space = [i for i in range(4096)]
# Recursive:
def binarySearchRec(arr, low, high, target):
if high >= low:
mid = (high + low) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binarySearchRec(arr, low, mid-1, target)
else:
return binarySearchRec(arr, mid, high, target)
else:
return -1
if __name__ == '__main__':
element = random.choice(space)
print(f"Index: {binarySearchRec(space, 0, len(space)-1, element)} | Number: {element}")
This should return answer in max 12 steps because O(log(N)) complexity. But some runs it exceeds max call stack. How can i prevent this i can't find why.
I will be preciate for an answer.
Hey Guys thank you for answers,
I also found a solution to problem. Every time target > arr[mid] i was returning low = mid. I changed this as low = mid + 1.
This solved the problem and it's worked as it opposed to last element found in 13 steps as it is supposed to be.
Code:
def binarySearchRec(arr, low, high, target):
if high >= low:
mid = (high + low) // 2
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binarySearchRec(arr, low, mid-1, target)
else:
return binarySearchRec(arr, mid+1, high, target)
else:
return -1