The simplest way to find something: look at every item, in order, until you find it or run out of items.
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.
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:
| Case | Comparisons | Why |
|---|---|---|
| Successful, best case | 1 | The target is the first element. |
| Successful, worst case | N | The target is the last element. |
| Successful, average | (N + 1) / 2 | If every position is equally likely, the search goes about halfway. |
| Failed search | N | Every 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 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.
Grey cells have been checked. The arrow is i.
This is the class code. The array and x in main() change to match what you search for.
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.