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
Post A Comment:
0 comments: