Sequential Search (Linear Search)

  • Sequential search is also called as Linear Search.
  • Sequential search starts at the beginning of the list and checks every element of the list.
  • It is a basic and simple search algorithm.
Sequential search compares the element with all the other elements given in the list. If the element is matched, it returns the value index, else it returns -1.

Complexity with example:

  34 56   21           09       76 1     98           50


Suppose,  key=34, we search it in array (where it is present or not in array)

Yes, It is present at arr[0] location that means we found it at 1st position,


We compare arr[i]==key and it takes O(1) time. This is the best time complexity of Linear search


Now we search key= 98, Again we compare arr[i]== key, it is located at 6th                        location, That means we get O(n) time complexity in average and worst case.

 


Pseudo Code: Linear Search


value=[2,5,6,9,1]

target= 9


function searchValue(value, target)

{

      for (var i = 0; i < value.length; i++)

      {

             if (value[i] == target)

             {

                     return i;

             }

      }

      return -1;

}



Program:
l=[]
def get():
n=int(input("Enter no of students in class SE: "))
for i in range(n):
k=int(input("Enter roll no= "))
l.append(k)

def dis():
for i in l:
print(i,end=" ")
# using for loop
def search():
i=0
key = int(input("Enter roll for searching whether "
"particular student attended training program or not "))
while(i<len(l)):
if key==l[i]:
print("Student attended session at", i, "location")
break
i+=1
if(i==len(l)):
print("Student did not attend session")

#using while loop
def linear():
cnt=0
key=int(input("Enter roll for searching whether particular "
"student attended training program or not "))
for i in range(len(l)):
if(key==l[i]):
print("Student attended session at", i , "location")
break
else:
cnt+=1
if(cnt-1==i):
print("Student did not attend session")
if __name__ == '__main__':
get()
dis()

print("\n1:Linear Search using for Loop")
print("3:Linear Search using for While")
ch=int(input("\nEnter choice"))
if(ch==1):
linear()
if(ch==3):
search()

Post a Comment

0 Comments