Skip to main content
Beginner ~8 min read

Linear Search

The simplest search: check every element until you find the target. Where it shines, where it fails, and how it compares to binary search.

Prerequisites: Arrays: Traversal, Insertion & Deletion

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

linear-search.js
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 / caseCostNotes
Best case (target first)O(1)—
Average caseO(n)≈ n/2 checks
Worst case (absent or last)O(n)—
SpaceO(1)just an index variable

Check your understanding

  1. 1.What does linearSearch return when the target is absent?
  2. 2.You must search a 1,000,000-element sorted array 500 times. Which is the better engineering call?
  3. 3.For which scenario is linear search genuinely the best choice?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Visualize it

Linear Search

Play, pause, and scrub the real algorithm step by step.

Play it

Binary Search Challenge

Pick the true midpoint of the search window each round and eliminate half the array. Miss twice and the hint a…

Keep going