Q. Estimate the number of key comparisons required in binary search and linear search if we need to find the details of a person in a sorted database having 230 (1, 073, 741, 824) records when details of the person being searched lies at the middle position in the database. What do you interpret from your findings?


Answer :-

At first you have to write this script:-

def linearSearch(list, key):
    found = 0
    for index in range(0,len(list)):
        if list[index] == key:
            return key ,"is at index :-", index+1 , " and number of key comparisons required ", index
    if found == 0 :
        return key ,"is not found !! And number of key comparisons required", index

def bisearch (ar, key):
    it = 0
    low = 0
    high = len(ar)-1
    while low <= high :
        it += 1
        mid = int ((low+high)/2)
        if key == ar[mid]:
            return key ,"is at index :-", mid , "Number of iterations required :-", it
        elif key < ar [mid]:
            high = mid - 1
        else :
            low = mid +1
    else :
        return key ,"is not found !! Number of iterations required: - ", it

lst = (1,73,741,824)

print( linearSearch (lst , 230))
print( bisearch (lst , 230 ))

Output:-

(230, 'is not found!! and number of key comparisons required', 3)
(230, 'is not found!! Number of iterations required:-', 2)

>>>

Post a Comment

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

Previous Post Next Post