Sub topic 1
What It Means to Search a Collection
Prerequisites
This chapter assumes you can write basic Python with loops, conditionals, and functions. It also assumes you know zero-based indexing for lists and the basics of Big-O notation.
The Search Problem
To search a collection, you take a sequence items and a target and return the index of an element equal to target. If no element matches, you return a sentinel value such as -1. Two questions decide which algorithm you can use:
- Is the data in any particular order?
- How often will you search the same data?
Linear Search: Checking Every Element
Linear search compares each element to the target in order. It stops at the first match.
def linear_search(items, target):
for i, value in enumerate(items):
if value == target:
return i
return -1
print(linear_search([4, 2, 7, 1], 7)) # 2
print(linear_search([4, 2, 7, 1], 5)) # -1Linear search makes no assumptions about order. It works on unsorted lists, linked lists, and streams.
How Long Linear Search Takes
With n elements, the number of comparisons depends on where the target is:
| Case | When it happens | Comparisons | Big-O |
|---|---|---|---|
| Best | Target is at index 0 | 1 | O(1) |
| Worst | Target is last or absent | n | O(n) |
| Average | Target is present, any position equally likely | (n + 1) / 2 | O(n) |
A common mistake is to treat the average case as faster than O(n). Halving the comparisons still leaves the cost growing in proportion to n.
The Sentinel Trick for Linear Search
The basic loop does two checks per step: "is the index still in range?" and "is this the target?" A sentinel search temporarily writes the target into the last slot. That guarantees the scan will find a match, so the range check can be dropped. After the scan, you restore the last element and check whether the match was real. This saves a constant factor in low-level languages, but the running time is still O(n). It also mutates the input, so it is unsafe on shared or read-only data.
Why Binary Search Needs Sorted Data
Binary search looks at the middle element and throws away the half that cannot contain the target. That step is only valid if the list is sorted. If a[mid] < target in a sorted list, every element to the left is also smaller than the target, so discarding the left half is safe.
On unsorted data that reasoning fails. In [9, 1, 7, 3, 5], searching for 9 checks a[2] = 7. Since 7 < 9, the search discards the left half and never sees the 9 at index 0. It returns -1 without raising any error. Sorting first costs O(n log n). That cost only pays off if you search the same data many times.
Exercise
A list of 1,000 unsorted IDs is searched once. Should you sort it and use binary search, or use linear search? Why?
Show answer
Use linear search. One search costs at most 1,000 comparisons (O(n)). Sorting alone costs O(n log n), which is about 10,000 comparisons, before the first binary search even starts.
Exercise
Why does the sentinel version of linear search still run in O(n) time?
Show answer
It removes one comparison per step, which changes only the constant factor. In the worst case it still visits every element.