Searching Algorithms

How Linear Search Works

Linear search checks each element in turn. It is the only search that needs no order at all, and the baseline every other search has to beat.

158
index 016 of 16 still possible15
  • Ruled out
  • Still possible
  • Checked now
  • Found
1/15

Looking for 158 in 16 sorted values, from 4 to 196.

Counters

Steps
0
Result
-
Still possible
16
of 16
Worst case
16
steps for this size

Settings

More options
Is it in the array?
Gaps between values

Two to 64 numbers. Sorted ascending before the search runs.

Linear search

  1. 1for i in 0..n-1:
  2. 2 if a[i] == target:
  3. 3 return i
  4. 4 if a[i] > target:
  5. 5 return NOT_FOUND // sorted
  6. 6return NOT_FOUND

The same array, every algorithm

Probes on the values above, cheapest first. One probe is one value actually looked at.

  1. Interpolation1
  2. Ternary3
  3. Binary4
  4. Jump5
  5. Exponential8
  6. Linear13

How the six compare

AlgorithmBestAverageWorstNeeds a sorted array
LinearO(1)O(n)O(n)No
BinaryO(1)O(log n)O(log n)Yes
TernaryO(1)O(log n)O(log n)Yes
JumpO(1)O(√n)O(√n)Yes
ExponentialO(1)O(log n)O(log n)Yes
InterpolationO(1)O(log log n)*O(n)Yes

Scroll the table sideways for the rest of the columns.

Interpolation search only reaches that average when the gaps between the values are even.

Complexity

BestAverageWorstExtra memory
O(1)O(n)O(n)O(1)

How linear search works

Linear search walks the list from one end, comparing each element with the target, and stops at the first match. It makes no assumptions: the data need not be sorted, indexed or even random-access, so a linked list or a stream works the same way. You pay for that generality by having no way to skip anything.

Implementation

JavaScript
function linearSearch(values, target) {
  for (let i = 0; i < values.length; i += 1) {
    if (values[i] === target) return i;
  }
  return -1;
}

When to use it

  • Use it on unsorted data, which is most data. Sorting a list to binary search it once costs more than scanning it.
  • Use it on small collections, where the constant factors dominate and a scan of twenty elements beats any cleverness.
  • Use it when the data arrives as a stream and you cannot jump around it at all.
  • Avoid it on large sorted collections you search repeatedly. That is what binary search is for.

More searching algorithms