To write a Python Program to perform binary search.
Python
def binary_search(alist, key):
"""Search key in alist[start... end - 1]."""
start = 0
end = len(alist)
while start < end:
mid = (start + end) // 2
if alist[mid] == key:
return mid
elif alist[mid] < key:
start = mid + 1
else:
end = mid
return -1
alist = input('Enter the sorted list of numbers: ')
alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('Enter the number to search for: '))
index = binary_search(alist, key)
if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))
OUTPUT:
Enter the sorted list of numbers: 1 2 3 4 5 6 7 8 9
The number to search for: 4
4 was found at index 3.