Linear Search
Linear search (or sequential search) is the most basic way to find a value: check each element from the start until you find it or run out of elements. It needs nothing from the data: no sorting, no special structure. That makes it the right tool for small or unsorted collections, and the baseline every faster search is compared with.
How it works
- Start at index 0.
- If the current element equals the target, return its index.
- Otherwise move to the next index.
- If you pass the end, the target is not there: return
-1(orNone).
Implementation
def linear_search(arr, target):
for i in range(len(arr)):
print(f"is arr[{i}] = {arr[i]} equal to {target}?")
if arr[i] == target:
return i
return -1
data = [14, 8, 23, 31, 5, 17]
print("index:", linear_search(data, 31))
print("index:", linear_search(data, 9))is arr[0] = 14 equal to 31?
is arr[1] = 8 equal to 31?
is arr[2] = 23 equal to 31?
is arr[3] = 31 equal to 31?
index: 3
is arr[0] = 14 equal to 9?
is arr[1] = 8 equal to 9?
is arr[2] = 23 equal to 9?
is arr[3] = 31 equal to 9?
is arr[4] = 5 equal to 9?
is arr[5] = 17 equal to 9?
index: -1
Finding 31 took four comparisons, the same as in the animation. A value that is missing costs a comparison with every element:
Best, worst and average case
| Case | When | Comparisons |
|---|---|---|
| Best | target is the first element | 1 |
| Worst | target is last or missing | n |
| Average (target present, any position equally likely) | about n / 2 |
All of these except the best case grow in proportion to n, so linear search is O(n).
def comparisons_needed(arr, target):
for i, v in enumerate(arr):
if v == target:
return i + 1
return len(arr)
data = list(range(100, 1100, 10)) # 100 values: 100, 110, ..., 1090
print("first :", comparisons_needed(data, 100))
print("middle:", comparisons_needed(data, 590))
print("last :", comparisons_needed(data, 1090))
print("absent:", comparisons_needed(data, 555))
average = sum(comparisons_needed(data, v) for v in data) / len(data)
print("average over all targets:", average)first : 1
middle: 50
last : 100
absent: 100
average over all targets: 50.5
Pythonic linear search
Python's in operator, list.index() and next() with a generator all perform a linear search for you. Use them in real code; they are implemented in C and much faster than a hand-written loop, though still O(n).
fruits = ["kiwi", "mango", "pear", "fig"]
print("pear" in fruits)
print(fruits.index("pear"))
# find the first item matching a condition, or a default
long_name = next((f for f in fruits if len(f) > 4), None)
print(long_name)
print(next((f for f in fruits if f.startswith("z")), "none found"))True
2
mango
none found
Note:
list.index()raisesValueErrorif the value is missing. Check withinfirst, or catch the exception.
Finding all matches and searching records
Linear search adapts easily: collect every matching index, or compare a field of each record instead of the whole item.
readings = [3, 7, 3, 9, 3, 1]
print([i for i, v in enumerate(readings) if v == 3])
books = [
{"title": "Dune", "year": 1965},
{"title": "Neuromancer", "year": 1984},
{"title": "Hyperion", "year": 1989},
]
def find_by_year(items, year):
for i, book in enumerate(items):
if book["year"] == year:
return i, book["title"]
return None
print(find_by_year(books, 1984))
print(find_by_year(books, 2001))[0, 2, 4]
(1, 'Neuromancer')
None
When is linear search the right choice?
- The data is unsorted and you search only once or a few times. Sorting first costs
O(n log n), more than a singleO(n)search. - The collection is small (a few dozen items): the simple loop is fast and has no overhead.
- The data is a linked list or a stream, where you can't jump to the middle anyway.
If you search the same large data many times, sort it once and use binary search, or put it in a hash set for O(1) lookups.
Test yourself
What does linear search require from the data?
- It must be sorted
- It must be stored in a hash table
- Nothing special
- Unique values
How many comparisons does linear search make on 1,000 elements when the target is missing?
- 1
- 10
- 500
- 1,000
What is the time complexity of linear search?
- O(1)
- O(log n)
- O(n)
- O(n²)