While trying to understand how recursion works in Python, I wrote the below function which searches a list for a given value. The idea is to sort the list then find the middle index within the ith and jth elements and comparing with the search value. The problem is that it goes into an infinite loop. I have run the statements step by step and the required result obtains. Can someone point out where I got it wrong?
def search(lst, v):
if not('i' in locals()) and not('j' in locals()):
i = 0
j = len(lst)
# sort
lst.sort()
midindex = i + int((j - i)/2)
if lst[midindex] > v:
j = midindex-1
return search(lst, v)
elif lst[midindex] < v:
i = midindex+1
return search(lst, v)
else:
return midindex