I was trying to execute the Binary Search program in python. I followed the algorithm steps yet it gives me this error. Here's my code:
def binarySearch(a,k,l,r):
if l > r:
return -1
else:
mid = (l+(r-l))//2
if(a[mid]>k):
return binarySearch(a,k,l,mid-1)
elif(a[mid]<k):
return binarySearch(a,k,mid+1,r)
else:
return mid
t = int(input("Enter no. of test cases: "))
for _ in range(t):
n,k = map(int, input().split())
a = list(map(int, input().rstrip().split()))
print(binarySearch(a,k,0,n))
Error:
return binarySearch(a,k,mid+1,r)
File "e:/Coding/Algorithms/Searching/binarySearch.py", line 10, in binarySearch
return binarySearch(a,k,mid+1,r)
File "e:/Coding/Algorithms/Searching/binarySearch.py", line 10, in binarySearch
return binarySearch(a,k,mid+1,r) [Previous line repeated 994 more times]
File "e:/Coding/Algorithms/Searching/binarySearch.py", line 3, in binarySearch if r < l:
RecursionError: maximum recursion depth exceeded in comparison
Your error lies in this line:
You need to divide
(r-l)//2
and then addl
but you are doing(l+(r-l))//2
which results in(l+r-l)//2 == r//2
.Change it to
l + (r-l)//2
.What happens is when this condition is true:
r
stays the same and since you are always dividingr
without consideringl
,mid
never changes. So, you get a recursion depth exceeded error.Also, the upper bound of the search is
n-1
wheren
is the length of the array. If then
in your function call is the length of the array (it isn't obvious from the code), you need to subtract one as follows: