I would like to implant recursive search using python, it will partition the upper part for the given key
example: list[2, 4, 6, 9, 10]
for the key is 6 case, the return index is 3
for the key is 4 case, the return index is 2
if the key is not in the list ie. the key is 7. It still needs to return with index 3 because 9 is greater than 7.
My code has issue to do recursive if the key is not in the array,
even I set boundary condition and I assume this will be ok, it cannot go through. Any advice is much appreciated.
def qReturn(alist, start, end, key):
if key is 1:
return 0
mid = (start + end)//2
if alist[mid] < key:
return qReturn(alist, mid + 1, end, key)
elif alist[mid] > key:
return qReturn(alist, start, mid, key)
if (start == end | end == mid | start > mid):
return mid+1
else:
return mid+1
alist = input('Enter the sorted list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))
index = qReturn(alist, 0, len(alist), key)
print('number q is at %d.' %index)
For example list [2, 4, 6, 9, 10] and key is 7
The code can not be terminated
What kind of boundary condition I need to set and get the result for upper partition for 7?