Sub topic 6
Linear Search
Assume you know basic arrays, loops, functions, and asymptotic notation. Linear search is the simplest way to find a value in a sequence. It checks elements from left to right until it finds the target or reaches the end.
Working Model
Let an array contain n elements. Linear search compares the target with the first element, then the second, and so on. It does not require the array to be sorted.
def linear_search(a, key):
for i, value in enumerate(a):
if value == key:
return i
return -1
numbers = [18, 7, 25, 11, 30]
print(linear_search(numbers, 11)) # 3
print(linear_search(numbers, 9)) # -1The function returns the index of the first matching element. It returns -1 when the target is absent.
Complexity and Cases
The number of comparisons depends on where the target appears.
| Case | Comparisons | Time |
|---|---|---|
| Best case: target is first | 1 | Θ(1) |
| Average successful case | About n/2 | Θ(n) |
| Worst case: target is last or absent | n | Θ(n) |
The worst-case time complexity is O(n), because the algorithm may inspect every element. The lower bound for the worst case is also Ω(n), so the worst-case complexity is Θ(n).
If every position is equally likely to contain a successful target, the average number of comparisons is
(n + 1) / 2.
This is still Θ(n), because constant factors do not change the asymptotic growth rate.
The algorithm uses Θ(1) extra space. The input array is not copied, and only the index and loop variables are stored.
Common GATE Patterns
- An unsuccessful search always performs n comparisons if the algorithm checks every element.
- A successful search may stop early, so its cost depends on the target position.
- If the target is uniformly distributed among n positions, the expected successful cost is (n + 1)/2 comparisons.
- Duplicate values do not change the worst-case bound. Returning the first match requires scanning from the beginning.
- Searching m independent arrays of length n takes Θ(mn) time.
A common error is to call linear search O(1) because the target might be found immediately. That describes only the best case, not the general or worst-case performance.
Exercise
An array has 10 distinct elements. A target is selected uniformly from the array, and linear search stops at the first match. What is the expected number of comparisons?
Show answer
(10 + 1) / 2 = 5.5 comparisons.