Binary Search

Binary search full python program code

Hey internet mates here we are going to make a python program to search for an element from a given list.

# To search an element in list using binary search method.

min=0
n=int(input("How many numbers you want enter:"))
max=n-1
f=0
# To create empty list.
lst=[]
# To append integers from user in the list.
for x in range(0,n):
    a=int(input("enter no:"))
    lst.append(a)
# To get search key from user.
sk=int(input("enter search key"))
# To sort list.
lst.sort()
# To search element.
while f!=1 and min<=max:
    mid=(min+max)//2
    if lst[mid]==sk:
        f=1
    elif lst[mid]>sk:
        max=mid-1
    else:
        min=mid+1
# To print result.        
if f==1:
    print("ITEM found in the list.",mid+1)
else:
    print("ITEM not found in the list.")

Leave a Comment

Your email address will not be published. Required fields are marked *