Write a Python Program to perform the binary search.



Program Algorithm:
1.Read the search element
2.Find the middle element in the sorted list
3.Compare the search element with the middle element
i. if both are matching, the print element found
ii. else then check if the search element is smaller or larger than the middle element
4.If the search element is smaller than the middle element, then repeat steps 2 and 3 for the
left sublist of the middle element
5.If the search element is larger than the middle element, then repeat steps 2 and 3 for the
right sublist of the middle element
6.Repeat the process until the search element if found in the list
7.If element is not found, loop terminates 

Program Code:
def bsearch(alist,item):
 first=0
 last=len(alist)-1
 found=False
 while first<=last and not found:
 mid=(first+last)//2
 if alist[mid]==item:
 found=True
 print("element found in position",mid)
 else:
 if item<alist[mid]:
 last=mid-1
else:
 first=mid+mid-1
 return found
a=[]
n=int(input("enter upper limit"))
for i in range(0,n):
 e=int(input("enter the elements"))
 a.append(e)
x=int(input("enter element to search"))
bsearch(a,x)




Program Output:
enter upper limit 6
enter the elements 2
enter the elements 3
enter the elements 5
enter the elements 7
enter the elements 14
enter the elements 25
enter element to search 5
element found in position 2 
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: