Write a Python Program to perform Linear Search. 

Program Algorithm:
1. Read n elements into the list
2. Read the element to be searched
3. If alist[pos]==item, then print the position of the item
4. Else increment the position and repeat step 3 until pos reaches the length of the list 

Program Code:
def search(alist,item):
 pos=0
 found=False
 stop=False
 while pos<len(alist) and not found and not stop:
 if alist[pos]==item:
 found=True
 print("element found in position",pos)
 else:
 if alist[pos]>item:
 stop=True
 else:
 pos=pos+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"))
search(a,x)  




Program Output:
Enter upper limit 5
Enter the elements 6
Enter the elements 45
Enter the elements 2
Enter the elements 61
Enter the elements 26
Enter element to search 6
Element found in position 1
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: