Search your topic here

Python Program to perform binary search

To write a Python Program to perform binary search. 

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:
            end = mid
        elif alist[mid] < key:
            start = mid + 1
        else:
            return mid
    return -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 = 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.

LEAVE A REPLY