Linear Search is the search equivalent of flipping through pages one by one: start at the first element and check each until you find the target or reach the end.
No clever math, no preprocessing, no assumptions about the data — that is its superpower. It works on any array, sorted or not, with zero setup.
How It Works
- Start at index 0.
- Compare the current element with the target value.
- If equal, return the index — you’re done.
- If not, move to the next element and repeat.
- If the array ends without a match, return -1.
Key Insight
The only “optimization” is the early exit on first match: stop the moment you find the target.
- Best case
O(1)— target at index 0. - Average / worst case
O(n)— full scan.
Because it never reorders or requires sorted input, it is the natural fallback when any fancier algorithm’s precondition (sortedness, uniform distribution) fails.
Worked Example
Search for 7 in [4, 2, 9, 7, 5]:
index 0:4 ≠ 7→ continueindex 1:2 ≠ 7→ continueindex 2:9 ≠ 7→ continueindex 3:7 = 7→ return 3
Search for 8 in the same array: the scan visits every element and returns -1. In the visualizer, the highlighted column advances one position per step.
Edge Cases & Pitfalls
- Empty array — return -1 immediately: nothing to scan.
- Duplicates — returns the first occurrence, not any particular later one.
- Unsorted data — Linear Search is the only correct simple option without sorting first.
- Large arrays —
O(n)scans waste time when sorted data givesO(log n). But for one-off reads on small data, constant factors favor Linear Search. - Early exit trap — don’t return -1 mid-loop because the current element is larger than the target. The array may be unsorted; a match could still be ahead.
Comparison With Other Searches
| Scenario | Linear Search | Binary Search | Jump Search |
|---|---|---|---|
| Requires sorted input | No | Yes | Yes |
| Average time | O(n) | O(log n) | O(√n) |
| Extra space | O(1) | O(1) | O(1) |
| Best when | Small / unsorted data | Large sorted data | Sorted + cheap jumps |
Applications
- Searching unsorted lists, logs, or streaming data with no preprocessing
- Finding the first occurrence (e.g., first unread message)
- Tiny arrays where the setup cost of sorting outweighs the scan
Practice Trajectory
- Hand-trace Linear Search on
[3, 8, 1, 6, 2]for target 6 and for target 9. - Explain why it returns -1 on an empty array without erroring.
- State the best-, average-, and worst-case number of comparisons for an array of size 5.
- Argue when you’d choose Linear over Binary Search even on sorted data.
- Implement it with an early exit and confirm it stops at the first match.