Python Program for Linear Search. Linear search, also known as sequential search, is one of the simplest search algorithms. It works by checking each element of a list or array sequentially until the desired element is found or the list ends this method is straightforward and does not require data to be sorted.
Table of Contents
When to Use Linear Search
Linear search is particularly useful when dealing with small or unsorted datasets where the simplicity of implementation is more critical than the efficiency of the search. It is the ease of understanding makes it a perfect starting point for learning about search algorithms.
Python Implementation of Linear Search
Let’s explore how to implement linear search in Python. we will create a function that takes two parameters: A list and the item to be searched. The function will return the index of the item if found; otherwise, it will return -1, Indicating the item is not in the list.
Define the Function
def linear_search(arr,x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
Explanation:
'arr'
: The list or array in which to search.'x':
The item to be searched- The
'for'
loop iterates over each element in the list. - The
'if'
statement checks if the correct element matches the item'x'
. - If a match is found, it returns the index
'i'
. - If no match is found by the end of the loop, the function returns
'-1'
.
Test the Function
To ensure our function works as expected, let’s test the linear search function.
arr = [34,65,12,54,67,87]
x = 67
result = linear_search(arr,x)
if result != -1:
print("The element is present at index: ",result)
else:
print("The element is not present in the array")
Linear Search Time Complexity
A time complexity of linear search is O(n)
, where n is the number of elements in the list. This is because, in the worst case, every element needs to be checked. This makes linear search inefficient for large datasets.
Linear search is an easy-to-understand and easy-to-implement algorithm suitable for small or unordered datasets. while not the fastest, its simplicity makes it an essential algorithm for beginners to learn and understand basic searching techniques in computer science.
Happy Coding & Learning
1 thought on “Python Program for Linear Search”