Python Program to Implement Binary Search Without Using Recursion

01. Example:

def binarySearch(data, start, end, key):
    
    start = 0
    end = len(data)
    
    while start < end:
      mid = (start + end)//2
      
      if data[mid] > key:
        end = mid
        
      elif data[mid] < key:
        start = mid + 1
      
      else:
        return mid
    
    return -1


list01 = input("Enter the sorted list of numbers: ")
list01 = list01.split()
list01 = [int(x) for x in list01]
key = int(input("The number to search for: "))

index = binarySearch(list01, 0, len(list01), 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: 320 420 140 500 185 60 200 80 10 100
The number to search for: 50
50 was not found.

 

Leave a comment