AP® Computer Science A · Unit 4 · Topic 4.14

Linear Search

Linear search checks each element in order, starting from the front, stopping the moment it finds the target and giving up only after checking every slot.

Linear search has no shortcuts because it has no information. An unsorted array gives you nothing to rule out, so the only honest way to find a target is to look at each element and ask: is this it? The algorithm walks the array from index 0, comparing the target to the current element. The moment they match, it stops and reports the index. If it reaches the end without a match, it reports that the target is not there, often with -1.

That -1 matters because it is a signal, not a position. Returning 0 would look like a real index, as if the target sat at the front of the array, but -1 can never be mistaken for a location since valid indices never go negative. Mixing these up is a common source of bugs when code checks the result of a search and tries to use it as an index without first checking for -1.

Counting comparisons makes the behavior concrete. If the target sits at position k (counting from 1), linear search makes exactly k comparisons, since it checks one element at a time from the start and stops the instant it matches. If the target is missing from an array of n items, the algorithm must check all n before concluding that, so it makes exactly n comparisons. This connects directly to binary search, which only works on sorted data but cuts the array in half each step instead of checking one element at a time, and to 2D arrays, where linear search has to sweep every row, treating the grid as one long sequence of elements to check.

Key terms

Linear search
An algorithm that checks array elements one at a time, in order, until it finds the target or runs out of elements.
Comparison
A single check of whether the current element equals the target value.
Sentinel value
A special return value, often -1, used to signal that the target was not found.
Unsorted array
An array with no guaranteed order, which forces a search to check every element rather than skip any.

Watch it explained

  1. How it worksHow does linear search stop the instant it finds a match, and keep going if it does not?
  2. Worked exampleTrace a linear search for 15 in {4, 9, 15, 22, 3} and count the comparisons.
  3. Worked exampleFind how many comparisons linear search makes when the target is missing from 8 items.
  4. Common mistakeWhy doesn't returning -1 for not found mean the same as returning 0?
  5. Going furtherWhat changes when linear search has to run across every row of a 2D array?

Check yourself

Your turn1 of 2
Linear search looks for a target that happens to sit at position 21 (counting the first position as 1) in an array, checking one element at a time from the start. How many comparisons does it make before finding it?

End of topic.