Linear search is exactly what it sounds like: walk the array from the start, compare each element with the target, and stop when you find it. If you reach the end, the target isn't there. It is the first search algorithm every programmer writes, and it remains the correct choice surprisingly often.
Best case O(1): the target is the first element. Worst case O(n): the target is last or absent, you checked everything. On average you inspect about half the array, which is still O(n). The key limitation: linear search cares nothing about order. A sorted array gains you nothing here, which is precisely the opportunity binary search exploits.
Implementation
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i; // first occurrence wins
}
}
return -1; // not found convention
}
// Works on any comparable data, any order:
linearSearch([4, 2, 7, 2, 9], 2); // 1 (first 2)
linearSearch([4, 2, 7], 42); // -1| Operation / case | Cost | Notes |
|---|---|---|
| Best case (target first) | O(1) | — |
| Average case | O(n) | ≈ n/2 checks |
| Worst case (absent or last) | O(n) | — |
| Space | O(1) | just an index variable |