Linear Search — Algorithm Visualized
Learn linear search — sequential scan O(n), works on unsorted arrays, step-by-step index highlight visualizer, code and complexity analysis.
Introduction
Linear search checks each element from left to right until the target is found or the array ends — O(n) time, O(1) space, works on unsorted data.
Quick index
| # | Section |
|---|---|
| 1 | How it works |
| 2 | Interactive visualizer |
| 3 | Full implementation |
| 4 | Complexity analysis |
| 5 | Real-life examples |
1. How it works
for i = 0..n-1: if arr[i] === target → return i
return -12. Interactive visualizer
Linear Search — Step Visualizer
Scan each element left to right until target is found or array ends.
Target: 7 · Start
Linear search — scan left to right
const target = 7 for (let i = 0; i < arr.length; i++) if (arr[i] === target) return i
Check each element until found or array exhausted.
Time
O(n)
Space
O(1)
Stable
—
3. Full implementation
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return i
}
return -1
}Function calls with output
// ── Demo calls — output shown on the right ──
const arr = [4, 2, 7, 1, 9, 3]
linearSearch(arr, 7) // → 2
linearSearch(arr, 1) // → 3
linearSearch(arr, 99) // → -14. Complexity analysis
| Case | Time |
|---|---|
| Best | O(1) — target at index 0 |
| Worst | O(n) — target absent or last |
| Space | O(1) |
5. Real-life examples
| Scenario | Why linear search |
|---|---|
| Finding a contact in unsorted phone list | No order — must scan each entry |
| Barcode scan mismatch | Check if SKU exists in unsorted shipment list |
| Ctrl+F in unsorted document | Scan text character by character |
| Checking username availability (small list) | Reserved names array — n < 100, linear is fine |
| Finding item in messy drawer | No index — check each object until found |
Warehouse return lookup
Scan unsorted daily return labels — must check each entry until found.
Today's returns — no sort order, FIFO scan required.
Real-world implementation
function linearSearch(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) return i
}
return -1
}Full working code for the scenario above.
Function calls with output
// ── Function calls with output ── const returns = ["R-8821","R-9012","R-7743","R-3301"]
Side output shows return value after each call — step through to trace execution.
Summary
Linear search is the baseline — simple, no preprocessing, optimal when n is small or data is unsorted.
Next reads: Binary Search · DSA Arrays
Subscribe to my newsletter
Stay up to date and get notified when I share new contents.
No spam ever, unsubscribe anytime