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