Back to Catalog
Algorithms
searching
Linear Search
Scan every element in sequence until you find the target — no preconditions, no setup, works on anything.
Intent & Description
🎯 Intent
Find an element in any collection with zero preconditions — no sorting, no indexing, no preprocessing required.
📋 Context
Your data is unsorted, the dataset is small, or you’re searching by a condition that can’t be addressed by a key. Any more complex algorithm would add setup cost that outweighs the gain.
💡 Solution
Walk the collection from index 0. Compare each element to the target. Return the index on a match; return -1 after exhausting the array.
Real-world Use Case
Unsorted collections where sorting first would cost more than the search itself. Small datasets where O(n) is negligible. One-off searches. Searching by an arbitrary predicate rather than equality on a sortable key.
📌 TL;DR
Walk every element until you find it — O(n), works on anything, zero setup. Reach for it when data is small, unsorted, or a one-off search.
Advantages
- Works on any collection — unsorted, partially sorted, or linked
- Zero setup — no sorting or preprocessing needed before the first search
- Dead simple to implement, read, and debug
Disadvantages
- O(n) per query — cost grows linearly with dataset size
- Unsuitable for repeated searches over large datasets — each query scans everything
- No early elimination — every element is examined on a miss
Implementation Example
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i; // Found at index i
}
}
return -1; // Not found
}
// Usage
const array = [10, 50, 30, 70, 80, 20];
console.log(linearSearch(array, 30)); // 2
console.log(linearSearch(array, 90)); // -1