Linear Search (Sequential Search) compares the target key sequentially with each element in the list from the first index ($0$) to the last ($n-1$) until either the key is located or the end of the collection is reached:
def linear_search(lst, target):
"""Searches for target in unsorted list. Returns index or -1."""
for i in range(len(lst)):
if lst[i] == target:
return i # Key found at index i!
return -1 # Key not present in list
Complexity:
- Best-case: $O(1)$ when the target is at index 0 (first comparison).
- Worst-case: $O(n)$ when the target is at the final index $n-1$ or not present at all ($n$ comparisons).
- Average-case: $O(n)$ (approx. $\frac{n+1}{2}$ comparisons).
- Advantage: Works on completely unordered, unsorted datasets.