Python Program to Implement Binary Search Using Recursion

01. Example:

def binarySearch(data, start, end, key):
    
    if not start < end:
        return -1

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


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