Data Structures · Searching

Linear search

The simplest way to find something: look at every item, in order, until you find it or run out of items.

The idea

Linear search scans an array (or vector, or list) from the first element to the last. At each position it asks one question: is this the value I want? If yes, it returns that position. If it reaches the end without a match, it returns -1 to mean "not here."

Linear search needs nothing from the data. The values can be in any order, there can be duplicates, and the data never has to be sorted first. That is its great strength, and the reason it is still used every day.

Counting the work

The natural way to measure a search is to count comparisons: how many times the code checks arr[i] == x. For an array of N elements:

What is the complexity of a successful search? Of a failed search? Think first, then open.
CaseComparisonsWhy
Successful, best case1The target is the first element.
Successful, worst caseNThe target is the last element.
Successful, average(N + 1) / 2If every position is equally likely, the search goes about halfway.
Failed searchNEvery element must be checked before we can say "not here."

Both the average successful search and every failed search grow in proportion to N, so linear search is O(N). Double the array and you double the work. The "Average it" experiment below lets you check these numbers yourself.

When is it the right choice?

When you search the same large collection many times, it pays to organize it first: sort it for binary search, or put it in a hash table. Those are the next topics.

The array

Grey cells have been checked. The arrow is i.

Variables

What is happening

Output

    linear_search.cpp

      This is the class code. The array and x in main() change to match what you search for.

      Average it

      Each run searches for every element once, plus values that are not in the array, and averages the comparisons. Compare the averages with (N + 1) / 2 and N.