Sub topic 7
Linear Search
This chapter assumes you can write loops and functions, index arrays, and read the O, Omega, and Theta notation from the earlier chapters. It covers the working model of linear search, its cost in the best, worst, and average cases, and the mistakes GATE questions most often probe.
The Working Model
Linear search scans a collection from the first element to the last. It compares each element with the key and stops at the first match. If it reaches the end without a match, it reports failure.
It needs no preparation of the data. The array can be unsorted, and the container can be a linked list as well as an array. That is its main advantage over binary search, which needs sorted data and random access.
def linear_search(a, key):
for i in range(len(a)):
if a[i] == key:
return i
return -1
data = [42, 7, 19, 7, 88]
print(linear_search(data, 19)) # 2
print(linear_search(data, 7)) # 1, the first match
print(linear_search(data, 100)) # -1The function returns the index of the first match. A later duplicate is never reached.
Cost Model
The cost model counts key comparisons, written a[i] == key. Loop bookkeeping adds only a constant factor per iteration, so it does not change the asymptotic class.
Let n be the array length.
| Case | Situation | Comparisons | Time |
|---|---|---|---|
| Best | Key is at index 0 | 1 | Theta(1) |
| Worst, key present | Key is at the last index | n | Theta(n) |
| Worst, key absent | Every element is checked | n | Theta(n) |
| Average, key present | Each position equally likely | (n + 1) / 2 | Theta(n) |
The average comes from the sum of the position numbers 1 through n, divided by n:
(1 + 2 + ... + n) / n = (n + 1) / 2
If the key is absent with probability q, and each position is equally likely otherwise, the expected number of comparisons is:
(1 - q)(n + 1) / 2 + q * n
At q = 0 this gives (n + 1) / 2. At q = 1 it gives n. Either way the growth is linear.
Stating Bounds Correctly
Linear search is O(n) in the worst case and Omega(1) in the best case. No single Theta bound covers all inputs, because the running time ranges from constant to linear. Saying "linear search is Theta(n)" without naming a case is imprecise. Saying "the worst case is Theta(n)" is correct.
Space is O(1). The search keeps only the index and the key, whatever the input size.
Variants
Sentinel Search
The plain loop does two tests per iteration: the bounds test and the match test. A sentinel removes the bounds test. You place a copy of the key at the end of the array, so the scan is sure to stop.
def sentinel_search(a, key):
n = len(a)
if n == 0:
return -1
last = a[n - 1]
a[n - 1] = key # sentinel
i = 0
while a[i] != key:
i += 1
a[n - 1] = last # restore
if i < n - 1 or last == key:
return i
return -1
print(sentinel_search([5, 3, 9, 1], 9)) # 2
print(sentinel_search([5, 3, 9, 1], 1)) # 3
print(sentinel_search([5, 3, 9, 1], 4)) # -1The comparison count drops from about 2n to about n + 1. The class stays O(n). The final check matters: reaching the last slot can mean either a real match there or only the sentinel.
Sorted Input
When the array is sorted ascending, the scan can stop as soon as a[i] > key. An unsuccessful search then ends early. The worst case is still n comparisons, so the class is unchanged. Binary search is the better tool on sorted arrays with random access.
Linked Lists
Binary search needs O(1) access to the middle element. A singly linked list does not give that, so linear search is the standard approach there. Each step follows a pointer, and the worst case remains O(n).
Common Errors
- Off-by-one in the bound. Looping to
len(a) - 1skips the last element. In Python the loop should berange(len(a)). - Returning 0 for failure. Index 0 is a valid position. Use -1 or a separate flag.
- Confusing comparisons with time. A search with 5 comparisons is not "O(5)". The count is a constant, so the time is O(1).
- Claiming the average is Theta(1). The average position is about n/2, which is linear.
- Forgetting duplicates. The plain version returns the first match. Finding all matches always takes n comparisons.
- Assuming a sorted array helps the worst case. The early-exit variant helps only some inputs.
A Worked Example
Take the array [14, 3, 27, 8, 3, 50] and the key 8.
- Compare 14 with 8. No match.
- Compare 3 with 8. No match.
- Compare 27 with 8. No match.
- Compare 8 with 8. Match at index 3.
That is 4 comparisons. For key 3, the search stops at index 1 after 2 comparisons. For key 99, it makes 6 comparisons and returns -1.
Counting Comparisons in Code
You can check the cost model by instrumenting the search.
def count_comparisons(a, key):
count = 0
for x in a:
count += 1
if x == key:
return count
return count
n = 10
a = list(range(n))
total = sum(count_comparisons(a, k) for k in a)
print(total / n) # 5.5, which equals (n + 1) / 2The printed average is 5.5, matching (10 + 1) / 2 for successful searches with uniformly distributed keys.
When to Use It
- The data is small. Constant factors then dominate, and the scan is hard to beat.
- The data is unsorted and you search once. Sorting first costs O(n log n), which is more than one scan.
- The container is a linked list or a stream.
- You must find every match, or the first match by a predicate rather than by equality.
For repeated searches on a large static array, sorting once and using binary search wins. For repeated searches by key, a hash table is faster on average.
Exercise
An array of 100 distinct elements is searched with plain linear search. Each of the 100 positions is equally likely to hold the key, and the key is always present. What is the expected number of comparisons, and what is the worst-case number for an unsuccessful search?
Show answer
The expected number for a successful search is (100 + 1) / 2 = 50.5 comparisons. An unsuccessful search compares every element, so the worst case is 100 comparisons. Both are Theta(n) in growth.
Exercise
Linear search runs on 8 elements. The key is absent with probability 1/4. Otherwise it is equally likely to be at any of the 8 positions. What is the expected number of comparisons?
Show answer
Use (1 - q)(n + 1) / 2 + q * n with q = 1/4 and n = 8. This gives (3/4)(4.5) + (1/4)(8) = 3.375 + 2 = 5.375 comparisons.