Linear Search, also known as sequential search, is the most straightforward searching algorithm. It sequentially checks each element of a list until a match is found or the whole list has been searched.
It's simple to understand and implement, but it's not the most efficient algorithm for large datasets.
The algorithm follows these simple steps:
Here is a simple function that implements the linear search algorithm.
def linear_search(data, target):
"""
Searches for a target value in a list.
Returns the index of the target if found, otherwise returns -1.
"""
for i in range(len(data)):
if data[i] == target:
return i # Target found, return its index
return -1 # Target not found
// --- Usage ---
my_list = [10, 23, 45, 70, 11, 15]
target_value = 70
result = linear_search(my_list, target_value)
if result != -1:
print(f"Element {target_value} is present at index {result}")
else:
print(f"Element {target_value} is not present in the list")
The performance of linear search is directly proportional to the number of elements in the list.
Because of its O(n) complexity, linear search is not suitable for large lists. For sorted lists, Binary Search is a much more efficient alternative.
When to use Linear Search? Despite its inefficiency on large lists, linear search is perfectly fine for small lists. It also has the advantage of not requiring the list to be sorted.
What is the worst-case time complexity of a linear search?