Linear Search in Python

Written by

Himani Kohli

Linear Search in Python

In this program, we will learn to search an element from the given array by using the linear search technique.

A linear or sequential search, as the name suggests, is done when you inspect each item in a list one by one from one end to the other to find a match for what you are searching for. 

As compared with other techniques it is the worst searching algorithm with worst-case time complexity O (n).

Algorithm: 

  1. Input the number to be searched from the user and store in variable n.
  2. Array a is initialized.
  3. Using for loop, perform the linear search.
  4. Check if n==a[i], if true print “Number found”.
  5. Also, return its index or position.
  6. Iterate till we found the desired number which is asked by the user.
  7. Exit.

Code:

n=int(input("Enter the number to be searched (1-10):"))

a=[1, 2, 4, 3,5,7,9,8,6,10 ]

for i in range(1,(len(a))):

    if n==a[i]:

        print("number found at",i+1)

 

Output:

Enter the number to be searched (1-10):7

Number found at 6

 

Linear Search in Python