Q. Write a program that takes as input a list of 10 integers and a key value and applies binary search to find whether the key is present in the list or not. If the key is present it should display the position of the key in the list otherwise it should print an appropriate message. Run the program for at least 3 different key values and note the results.

Answer :-

def bisearch (ar, key):
    low = 0
    high = len(ar)-1
    while low <= high :
        mid = int ((low+high)/2)
        if key == ar[mid]:
            return mid
        elif key < ar [mid]:
            high = mid - 1
        else :
            low = mid +1
    else :
        return -999
lst = eval(input ("Enter a List :-"))
key = int (input("Enter search key : " ))
res = bisearch(lst , key)
if res >= 0:
    print (key , "FOUND at index ", res+1)
else :
    print ("Sorry ! ",key ,"Not FOUND in list")

Output:-

Enter a List :-[12,16,19,21,26,59,86,92,97]
Enter search key : 19
19 FOUND at index  3
>>>

Enter a List :-[12,16,19,21,26,59,86,92,97]
Enter search key : 59
59 FOUND at index  6
>>>

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post