Searching Algorithms in Python

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Program 1

# Program for Linear  Search
mylist=[]
n=int(input("Enter the limit"))
print("Enter elements in list")
for i in range(0,n,1):
    x=int(input())
    mylist.append(x)
s=int(input("Enter an element for search"))
flag=False
for m in mylist:
     if(s==m):
          flag=True
          break
if(flag):
     print("Searching is sucess")    
else:
     print("Searching not is sucess")         

Program 2

# Program for Binary  Search
mylist=[]
n=int(input("Enter the limit"))
print("Enter elements in list")
for i in range(0,n,1):
    x=int(input())
    mylist.append(x)

mylist.sort()
print(mylist)
s=int(input("Enter an element for search"))
low=0
high=n-1
flag=False
while(low<=high):
    mid=(low+high)//2
    if(s==mylist[mid]):
        flag=True 
        break
    elif(s>mylist[mid]):
        low=mid+1
    else:
        high=mid-1
if(flag):
     print("Searching is sucess")    
else:
     print("Searching not is sucess")    

 

Your opinion matters
Please write your valuable feedback about DataFlair on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

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