AlgoFrames

Linear search

Linear search checks each element from left to right until it finds the target. It works on any array and takes O(n) time.

The idea

You look for a friend on a guest list written in arrival order. Nothing tells you where the name is, so you read from the top.

Linear search is this habit written as code. It is the search that works on any list, sorted or not.

Intuition

We want 8. The values are in no order, so one value tells us nothing about the others.

So check each value from left to right. Each miss rules out one cell, and the first match ends the search.

Complexity

A missing target costs n checks. A present one costs about n / 2 on average, which is still O(n).

Doubling the array doubles the work. For a million values the worst case is a million checks.

The best case is one check, when the target sits at index 0. Space is O(1): only i is stored.

Pitfalls

A common bug returns -1 inside the loop on the first miss. Return -1 only after the loop ends.

A loop written as i ≤ n checks all 8 cells, then reads a[8], one past the last index. Stop at i < n.

Variations

To count matches, keep scanning after a match and add one each time. The cost stays O(n).

Sentinel search puts a copy of the target after the last cell. The loop then needs no end check.

On sorted values binary search needs only about log2 n checks instead of n.

Code

Pseudocode

for i ← 0 to n - 1
  if a[i] = target: return i
return -1

Python

def linear_search(a, target):
    for i in range(len(a)):
        if a[i] == target:
            return i
    return -1

JavaScript

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

Java

static int linearSearch(int[] a, int target) {
    for (int i = 0; i < a.length; i++) {
        if (a[i] == target) return i;
    }
    return -1;
}

Cost at a glance

TimeO(n)
SpaceO(1)
InputAny array
OutputIndex of the first match or -1

Practice problems (6)

Index of target Warm-up

Given an array of integers nums in any order and a target, return the index of the first cell equal to target. Return -1 if no cell holds it.

Worst case Warm-up

Linear search scans [7, 3, 9, 1, 8, 4, 6, 2] from left to right. Which target makes it do the most checks?

Count occurrences Standard

Given an array of integers nums in any order and a target, return how many cells are equal to target.

Last index of target Standard

Given an array of integers nums in any order and a target, return the index of the last cell equal to target. Return -1 if no cell holds it.

Trace a linear scan Standard

Follow linear search for 7 in [6, 2, 9, 2, 7, 5] and answer each question before the step plays.

Search with a sentinel Challenge

Return the index of the first cell of nums equal to target, or -1 if there is none, using a sentinel.

Append target to the end of nums first. The scan loop must then test only nums[i] != target, with no i < n check, because the sentinel always stops it. Remove the sentinel before you return, so nums is unchanged.

Related topics

Next on the path: Binary search