Write the input in python( Recursive Binary search)
Output:
Enter the sorted list number: 4 5 6 7 8 9 10
The number to search for :7-
7 was found at index 3
Answers
Answered by
2
INPUT:-
def binary_search(alist, start, end, key):
if not start < end:
return -1
mid = (start + end)//2
if alist[mid] < key:
return binary_search(alist, mid + 1, end, key)
elif alist[mid] > key:
return binary_search(alist, start, mid, key)
else:
return mid
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 = binary_search(alist, 0, len(alist), key)
if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))
Similar questions