1. Linear search
Linear (sequential) search checks the items one by one from the start until it finds the key or runs out.
def linear_search(a, x):
for i in range(len(a)):
if a[i] == x:
return i
return -1
It works on any list: unsorted, sorted, or a linked list. It needs no extra space.
| Case | Comparisons |
|---|---|
| Best (key first) | 1 |
| Worst, or key absent | |
| Average, key present, each position equally likely |
The average comes from . If the key is present only with probability , the expected count is .
So linear search is in the worst and average case. It is the right choice for a small list, an unsorted list searched only once or twice, or a structure without random access.
A sentinel variant puts the key at the end of the array so the loop needs no bounds check; the comparison count stays .