Finding an Item with Linear Search
Linear search finds a target by checking elements one at a time in sequence. You can use it to locate a stock code, a name, or another value in a collection whose order gives you no shortcut. Here, you will search from the beginning, return the first matching position, and report failure only after checking every available element.
Search from left to right
Start at the first element and compare its value with the target. If they match, return that element's index. Otherwise, advance to the next element and repeat. If you reach the end without a match, report that the target was not found.
An equality comparison is one test of whether an inspected value equals the target. Keep that test separate from checks that control the loop, such as checking whether another position exists.
Example: Searching the illustrated list for 77 compares 31, 58, 12, and 77 with the target. The search returns index 3 after four equality comparisons. It does not inspect 46 because the requested match has already been found.
If a value occurs several times, stopping at the first match returns its lowest index. Finding every occurrence would require continuing the scan, which changes the requested result and the amount of work.
Count the work
Let n be the number of elements and C the number of equality comparisons. With indices starting at zero, the governing count is:
The extra one in k+1 matters: index zero is the first element inspected, so reaching index three requires four comparisons.
Search outcome | Equality comparisons | Reason |
|---|---|---|
Match at the first element | 1 | The first test succeeds. |
First match at index k | k+1 | Every earlier element fails. |
Match only at the last element | n | Every position is inspected. |
Target absent | n | Every position must be ruled out. |
Empty collection | 0 | No element is available to compare. |
For a nonempty collection, the best case takes one comparison and the worst case takes n. The worst-case work therefore grows in direct proportion to collection size, written O(n).
An average depends on the searches being performed. If a target is guaranteed to occur exactly once and each of the n positions is equally likely, the average is (n+1)/2 comparisons. Do not apply this average automatically when searches can fail or some targets are requested more often.
Implement the stopping rules
This Python function returns an index when successful and uses −1 to mean not found:
def linear_search(values, target):
for index in range(len(values)):
if values[index] == target:
return index
return -1The successful return belongs inside the equality test. The failure return belongs after the loop, where reaching it means that no inspected element matched. An empty list skips the loop and returns −1 immediately.
The method works with sorted or unsorted data because it relies only on testing equality. Its reliability comes from inspecting every necessary position and using the stopping rules consistently.
What to remember
- Check elements in sequence, starting at index zero.
- Return immediately when the first match is found.
- Report failure only after exhausting the collection.
- Count inspected elements, not the numerical value of the returned index.
Example: Finding Stock Codes with Linear Search
Example: A stockroom app stores the codes [420, 175, 608, 175, 932, 517] in arrival order. The target is the stock code requested by the user. For each request, the app starts at index zero, returns immediately at the first match, and returns -1 if no match exists. Count only equality comparisons between a stored code and the target.
a) Search for 175. State the returned index and the number of equality comparisons.
The first inspected value, at index 0, is ________. It differs from 175, so the first comparison fails and the search advances.
The next inspected value, at index 1, is ________. It equals the target, so the second comparison succeeds. Because the app returns immediately, it never reaches the duplicate at index 3.
The comparison count is:
The app returns index 1 after 2 equality comparisons.
b) Search for 517. State the returned index and the number of equality comparisons.
The values at indices 0 through 4 are 420, 175, 608, 175, and 932. None equals 517, so the app rejects ________ values before inspecting the final position.
At index 5, the stored code is ________, which matches. Include this successful test in the total:
The app returns index 5 after 6 equality comparisons. The index is one smaller than the comparison count because indexing begins at zero.
c) Search for 888. State the returned result and comparison count, then find the total comparisons across all three requests.
Compare 888 with each stored code in order: 420, 175, 608, 175, 932, and 517. All six comparisons fail. Only after inspecting the last value can the app conclude that the target is absent.
For this request, the app returns -1 after 6 equality comparisons. The value -1 reports failure; it is not a comparison count.
Each request begins a new search. The first two requests together used ________ comparisons, so the combined workload is:
The three requests require 14 equality comparisons in total. An unsuccessful search still checks every element, even though it returns no matching index.
A library program uses sequential search to locate a requested catalogue number among stored catalogue numbers. Match each term to its meaning in this search.
A test that decides whether two values are the same
The stored item currently being checked against the requested value
An outcome reached after every stored item has been checked without finding a match
The target value supplied to the algorithm
Candidate
Search key
Equality comparison
Unsuccessful search
A parcel app uses first-match linear search with zero-based indices, returning -1 when a target is absent. Its main list is [81, 26, 57, 26, 94]. Complete each independent search below with exact integer results. Count only comparisons between an element and the target, and restart at the beginning for each row.
| Collection | Target | Returned index | Equality comparisons |
| Main list | 57 | ||
| Main list | 26 | ||
| Main list | 42 | ||
| Empty list | 42 |