Linear Search in Python
Harshit Jindal
Jan 03, 2023
Feb 24, 2021
Python
Python Algorithm

Note
If you want to understand Linear Search in detail then refer to the Linear Search Algorithm article.
Linear Search Algorithm
Let us assume that we have an unsorted array A[]
containing n
elements, and we want to find an element - X
.
-
Traverse all elements inside the array starting from the leftmost element using a
for
loop and do the following:- If the value of
A[i]
matches withX
, then return the indexi
. (If there can be multiple elements matchingX
, then instead of returning the indexi
, either print all indexes or store all the indexes in an array and return that array.) - Else move on to the next element.
- If it is at the last element of the array, quit the
for
loop.
- If the value of
-
If none of the elements matched, then return
-1
.
Linear Search Python Implementation
def linearsearch(arr, n, x):
for i in range(0, n):
if (arr[i] == x):
return i
return -1
arr = [1, 2, 3, 4, 5]
x = 1
n = len(arr)
position = linearsearch(arr, n, x)
if(position == -1):
print("Element not found !!!")
else:
print("Element is present at index", position)
Output:
Element is found at index: 1
The time complexity of the above algorithm is O(n)
.