Linear Search
The Linear Search algorithm, also known as Sequential Search, is a simple searching algorithm that sequentially checks each element of a collection until a match is found or the entire collection is traversed.
Algorithm Overview
Start with the first element of the collection.
Compare the target element with the current element.
If a match is found, return the index of the current element.
If the target element is not found, move to the next element and repeat steps 2-3.
Continue this process until the target element is found or the end of the collection is reached.
Note
Linear Search has a time complexity of O(n), where ‘n’ is the number of elements in the collection.
Example
Implementation in Python
Here’s a Python implementation of the Linear Search algorithm:
1 def linear_search(target: Any, items: List[Any]) -> Optional[int]:
2 for i, num in enumerate(arr):
3 if num == target:
4 return i
5 return None
Usage
To use the linear_search function:
1 from algorithms import linear_search
2
3
4 arr = [4, 2, 7, 1, 9, 5]
5 target = 7
6 index = linear_search(arr, target)
7 if index:
8 print(f"Element {target} found at index {index}")
9 else:
10 print(f"Element {target} not found")