BINARY SEARCH IN PYTHON
WRITE A PROGRAM FOR BINARY SEARCH
def Binary_Search(MyList,key):
low=0
high=len(MyList)-1
while low<=high:
mid=(low+high)//2 #find the middle index
if MyList[mid]==key: #if entered key matches the mid index element
return mid #return mid index
elif key>MyList[mid]: #else if key is greater
low=mid+1
else:
high=mid-1
return -1 #if no match,return -1
MyList=[10,20,30,40,45,56,69,88]
print(MyList)
key=(eval(input("Enter the number to search:")))
x=Binary_Search(MyList,key)
if(x==-1):
print(key,"is not present in the list")
else:
print("The Element",key,"is found at the position",x+1)
EXPLANATION:-
In the above program,we have defined the list with the elements [10,20,30,40,45,56,69,88]. The number to be searched is prompted from user.The list and the number to be searched both are passes as parameters to the function.In each iteration, the value of low , middle and high is calculated. The element to be searched, i.e the key element is compared with the middle element. Then depending on the condition,i.e the value of the key element and the element found at the mid position,the values of low and high are changed.
PROGRAM:-
OUTPUT:-
ALSO SEE:-
Comments
Post a Comment