Skip to main content

Linear Search

Watch a scan check every element until the target appears, and count the comparisons it costs.

time O(n)space O(1)Read the lesson
BeginnerO(n)

Watch a scan check every element until the target appears, and count the comparisons it costs.

step 1 / 6

What's happening

Linear search checks every element from left to right, looking for 8. Starting at index 0.

comparisons: 0n: 7
checking nowalready checkedfound

Linear search never needs order, that flexibility is exactly why it can't skip anything. Sorted input unlocks binary search's O(log n) halving instead.

Understand the algorithm

time O(n)space O(1)

What it is

Linear search scans an array from the first element to the last, comparing each value with the target until it finds a match or runs out of elements.

Why it matters

It is the baseline of all searching: the simplest correct algorithm, the one every other search is measured against, and the only one that works on unsorted data. Understanding why it must touch every element is the first step to understanding what binary search buys you.

How it works

  1. 1Start at index 0.
  2. 2Compare the current element with the target, equal means done.
  3. 3Otherwise move one position right and repeat.
  4. 4If the array ends first, the target is not present: return -1.

Real-world uses

  • Looking up an item in an unsorted list (a shopping list, a settings array)
  • Searching tiny collections where sorting would cost more than it saves
  • The fallback inside hash tables when many keys collide

Strengths

  • Works on any array, no ordering required
  • Simple to implement correctly; no edge-case traps
  • O(1) space and excellent for small n

Limitations

  • O(n) worst case, the cost grows in direct proportion to the data
  • Cannot skip anything: 1,000,000 items may need 1,000,000 comparisons
  • Sorted input buys nothing unless you switch to binary search

Works on any array, sorted or not.