Hello everyone, welcome back to programminginpython.com! Here I am going to explain to you how to implement linear search algorithm in python. This linear search is a basic search algorithm which searches all the elements in the list and finds the required value. This is also known as sequential search.
Here in this technique, I compare each and every element with the key element to be found, if both of them matches, the algorithm returns that element is found and its position.
You can also watch the video on YouTube here
Code Visualization – Linear Search Algorithm
Time Complexity
Best Case | O(1) |
Average Case | O(n) |
Worst Case | O(n) |
Algorithm
Given a list L
of n
elements with values or records,L0 ... Ln-1
and key/target element K
, linear search is used to find the index/position of the target K
in list L
- Initialize a boolean variable
found
and set it to False initially - Start for loop with
i
ranging from 0 to the length of the list - Check if key element is equal to
L[i]
- if equals
- set
found
boolean variable toTrue
- print the position of the element found
- break for loop
- set
- if equals
- If the boolean variable
found
is equal toFalse
after for loop, print that the element is not found in the list
Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
__author__ = 'Avinash' lst = [] num = int(input("Enter size of list: \t")) for n in range(num): numbers = int(input("Enter any number: \t")) lst.append(numbers) x = int(input("\nEnter number to search: \t")) found = False for i in range(len(lst)): if lst[i] == x: found = True print("\n%d found at position %d" % (x, i)) break if not found: print("\n%d is not in list" % x) |
Output


Same algorithm in other programming languages
In C language: http://www.mycodingcorner.com/2015/01/c-linear-search.html
In CPP language: http://www.mycodingcorner.com/2015/03/cpp-program-for-implementing-linear-search-technique.html
In Java language: http://www.mycodingcorner.com/2015/01/java-linear-search.html