Mental model
You are looking for one particular key on a ring of unlabelled keys. There is no order to exploit, so you try them one at a time. You stop as soon as one fits; if none fits, you have tried them all.
That is the whole algorithm:
- Start at index 0.
- If the index is past the end, report "not found" (−1).
- If the element equals the target, report its index and stop.
- Otherwise move to the next index and go back to step 2.
Stopping at the first match is the early exit. It means the result is the first occurrence when the value appears more than once, and that elements after the match are never read.
What the lab shows
The array sits on a row of slots. A pin marks i. Each element is first compared (≠ or =), and
elements that have been ruled out fade. Two counters run side by side:
- Comparisons: element-versus-target equality tests.
- Bounds checks: evaluations of the loop condition
i < n.
They differ by exactly one when the target is missing: the loop condition runs one last time, finds
i = n, and the loop ends. Keep that extra check in mind for the sentinel section below.
The only precondition: equality
Binary search needs sorted data, and a hash set needs a hash function consistent with equality. Linear search needs neither. It works on unsorted arrays, linked lists, streams you can only read once, and data that cannot be ordered at all. The one thing it relies on is that "equals" means what you think it means:
- Floating point NaN.
NaN == NaNis false in all four languages, so a search that uses==never finds NaN. The library searches disagree here: C#'sArray.IndexOfusesEquals, anddouble.NaN.Equals(double.NaN)is true; Java'sList.indexOfusesDouble.equals, also true; C++'sstd::finduses==, so it never finds NaN. Python'sinandlist.indexcheck identity before equality, so they find the same NaN object but not a different NaN. - Reference types. Equality must be value equality (
Equals/equals/__eq__/operator==) when you mean "the same contents", not reference identity. - Custom equality. If you search case-insensitively or by a field, pass that rule explicitly (the teaching implementations accept an equality comparer or function).
Cost
Let n be the number of elements.
| Case | Comparisons | Bounds checks |
|---|---|---|
| Target at index 0 (best) | 1 | 1 |
| Target at index k | k + 1 | k + 1 |
| Target absent (worst) | n | n + 1 |
| Present, every position equally likely (average) | (n + 1) / 2 | (n + 1) / 2 |
Time is Θ(n) in the worst case and O(1) in the best; extra space is O(1). The average assumes the target is present and equally likely to be anywhere. If it is often absent, expect close to n.
The important asymmetry: finding an element can be cheap, but proving that it is absent always costs n comparisons. Without order or hashing, no element tells you anything about the others, so every one must be checked.
The sentinel trick, honestly
The loop makes two tests per element: i < n and a[i] == target. The classic sentinel version
(described by Knuth) removes the first one:
a[n] = target // a spare slot just past the end
i = 0
while a[i] != target: // guaranteed to stop: the sentinel matches
i = i + 1
return i < n ? i : -1 // one bounds check, at the very end
What it saves: n bounds checks become one. In the absent case the plain loop makes 2n + 1 tests (n comparisons, n + 1 bounds checks); the sentinel loop makes n + 2 (n + 1 comparisons, the last one against the sentinel, plus the final check).
What it costs:
- A writable spare slot. Fixed-size arrays in C#, Java and C++ have no slot at index n. You must allocate one, or temporarily overwrite the last element and restore it afterwards (handling the case where the last element is itself the target).
- Mutation of the data. The search writes to the array, so it cannot run on read-only or
constdata, and two threads cannot search the same array at once. - Less obvious code for a gain you have to measure.
On current hardware the gain is usually small. The i < n branch is almost perfectly predicted, the
loop is limited by reading memory rather than by the comparison, and managed runtimes can already
remove the separate array bounds check inside a simple for (i = 0; i < a.Length; i++) loop.
Library searches over primitive types (for example .NET's Span<T>.IndexOf or C's memchr) compare
several elements per instruction with SIMD, which tends to matter more than a sentinel. Treat the
sentinel as a lesson in removing work from an inner loop, and reach for it only when a profiler says
that loop is the problem.
When a linear scan is the right choice
- Unsorted data, one query. Sorting first costs O(n log n), more than the O(n) scan it replaces.
- Small n. For a few dozen elements, a scan over contiguous memory is hard to beat.
- No random access. A singly linked list or a stream cannot be binary searched.
- A predicate, not a value. "The first order over 100 euros" is a scan with a condition.
When you will search the same data many times, change the data structure instead: sort once and use binary search (O(log n) per query), or build a hash set or map (expected O(1) per query). With q queries over n elements, q scans cost about q·n; sorting costs about n log n once plus q log n.
Language notes
| Language | Value search | Not found | Predicate search |
|---|---|---|---|
| C# | Array.IndexOf(array, x), list.IndexOf(x), span.IndexOf(x) |
−1 | Array.FindIndex, list.FindIndex, LINQ First/FirstOrDefault |
| Python | x in seq (bool), seq.index(x) |
index raises ValueError |
next((i for i, v in enumerate(seq) if pred(v)), -1) |
| Java | list.indexOf(x), list.contains(x) |
−1 | IntStream.range(0, n).filter(...).findFirst() |
| C++ | std::find(first, last, x), std::ranges::find(r, x) |
returns last |
std::find_if, std::ranges::find_if |
Two traps:
- Java has no
indexOffor arrays.Arrays.asList(array).indexOf(x)works for object arrays such asInteger[], butArrays.asList(intArray)makes a list with one element, theint[]itself, so the search silently returns −1. Loop over primitive arrays yourself. - Python's
list.indexraises instead of returning −1. Check withinfirst (two scans) or catchValueError(one scan).
The teaching implementation
IndexOf / linear_search / indexOf returns the first matching index or −1 and accepts an
optional equality rule, so the tests can count comparisons. All four read one shared fixture whose
last column is the exact number of comparisons the early-exit loop must make, and each is compared
with its language's built-in search on 2,000 random arrays.
Common mistakes
- Returning −1 inside the loop (
else return -1): the search then gives up after the first element. i <= nas the loop condition: reads one element past the end.- Searching for NaN with
==, or comparing references when you meant values. - Calling
Containsand thenIndexOf: two scans where one would do. - Scanning inside a loop over the same data: q·n work that a set or a sorted copy avoids.
Edge cases
- Empty array: one bounds check, zero comparisons, −1.
- Target appears several times: the first index is returned; the scan never sees the others.
- Target is the last element: the same number of comparisons as an absent target, but a different answer.
Worked practice
1. An array has 1,000 elements and the target is missing. How many comparisons and how many bounds checks does the early-exit loop make?
Answer
1,000 comparisons and 1,001 bounds checks: every element is compared once, and the loop condition
runs one extra time to discover that i reached 1,000.
2. You must answer 10,000 membership queries against the same 1,000,000 unsorted IDs. What do you do?
Answer
Not 10,000 linear scans (around 10¹⁰ comparisons in the worst case). Build a hash set once (O(n) expected) and answer each query in expected O(1), or sort once and binary search each query in about 20 comparisons.
3. Why does the sentinel version return i < n ? i : -1 instead of just i?
Answer
The loop always stops, either at a real match (i < n) or at the sentinel (i = n). Only the
first is a genuine result; stopping at the sentinel means the target was not among the original n
elements.
Summary
- Linear search checks elements in order and stops at the first match: O(n) worst, O(1) best, O(1) space.
- Its only precondition is a meaningful equality test; it needs no order and no hashing.
- Proving absence always costs n comparisons.
- A sentinel removes the per-element bounds check but needs a writable spare slot; measure before using it.
- For repeated queries, sort once or build a hash set instead.