# Linear Search

> Scan every element in sequence until you find the target — no preconditions, no setup, works on anything.

- **Category**: Algorithms
- **Subcategory**: searching
- **Canonical URL**: https://designpattern.fyi/algorithms/linear-search/

---

## 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.



## Use Cases
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.



## Implementation Example

```javascript
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
```



## Trade-offs


### 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




### Considerations & Drawbacks

- 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







