What is a Linear Search?
Linear search is a method of finding elements within a list. It is also called a sequential search. It is the simplest searching algorithm because it searches the desired element in a sequential manner.
It compares each and every element with the value that we are searching for. If both are matched, the element is found, and the algorithm returns the key’s index position.
Concept of Linear Search
Let’s understand the following steps to find the element key = 7 in the given list.
Step – 1: Start the search from the first element and Check key = 7 with each element of list x.
Step – 2: If element is found, return the index position of the key.
Step – 3: If element is not found, return element is not present.
Linear Search Algorithm
There is list of n elements and key value to be searched.
Below is the linear search algorithm.
- LinearSearch(list, key)
- for each item in the list
- if item == value
- return its index position
- return -1
Let’s understand the following Python implementation of the linear search algorithm.
Search function with parameter list name and the value to be searched
for i in range(len(list)): if list[i] == n: return True return False
list which contains both string and numbers.
list = [1, 2, ‘sachin’, 4,’Geeks’, 6]
n = ‘Geeks’
if search(list, n):