M12 · Searching

Linear Search and Its Preconditions

Linear search looks at the elements one by one and stops at the first match. It needs nothing from the data except a way to test equality, which makes it the search you fall back on whenever binary search or a hash table does not apply. This lesson counts exactly what it costs and looks honestly at the classic sentinel optimisation.

~25 minBeginnerC# · Python · Java · C++
Curriculum: M12 Searching · 3 of 3 lessons available

You will be able to

  • Trace a linear search and say after each step which elements have been ruled out.
  • Count comparisons and bounds checks in the best, worst and average case, and explain why proving absence always costs n comparisons.
  • State the only precondition linear search has (a meaningful equality test) and recognise where equality is surprising, such as NaN.
  • Explain the sentinel technique, what it saves, what it requires, and why the gain is small on current hardware.
  • Pick between a linear scan, sorting plus binary search, and a hash set for a given number of queries.

Helpful before this lesson

  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.
  • M05 Arrays — Contiguous storage, index arithmetic, and how a dynamic array grows while keeping append cheap.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

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:

  1. Start at index 0.
  2. If the index is past the end, report "not found" (−1).
  3. If the element equals the target, report its index and stop.
  4. 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 == NaN is false in all four languages, so a search that uses == never finds NaN. The library searches disagree here: C#'s Array.IndexOf uses Equals, and double.NaN.Equals(double.NaN) is true; Java's List.indexOf uses Double.equals, also true; C++'s std::find uses ==, so it never finds NaN. Python's in and list.index check 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 const data, 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 indexOf for arrays. Arrays.asList(array).indexOf(x) works for object arrays such as Integer[], but Arrays.asList(intArray) makes a list with one element, the int[] itself, so the search silently returns −1. Loop over primitive arrays yourself.
  • Python's list.index raises instead of returning −1. Check with in first (two scans) or catch ValueError (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 <= n as the loop condition: reads one element past the end.
  • Searching for NaN with ==, or comparing references when you meant values.
  • Calling Contains and then IndexOf: 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.

Full implementation

Linear search in four languages, each checked against one shared fixture (empty, one element, first, last, duplicates, missing, extremes) including the exact number of comparisons, and 2,000 random arrays compared with the language's built-in search (Array.IndexOf, list.index, List.indexOf, std::find).

namespace Bekadan.Dsa.Examples.Searching;
 
/// <summary>
/// Linear search with an early exit: the index of the first element equal to
/// the target, or -1. Works on unsorted data. O(n) comparisons in the worst
/// case, 1 in the best; O(1) extra space.
/// </summary>
public static class LinearSearch
{
    public static int IndexOf<T>(T[] items, T target, IEqualityComparer<T>? comparer = null)
    {
        comparer ??= EqualityComparer<T>.Default;
        for (int i = 0; i < items.Length; i++)
        {
            if (comparer.Equals(items[i], target))
            {
                return i; // the first match: stop early
            }
        }
        return -1; // compared every element
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Searching/LinearSearch.cs

"""Linear search with an early exit.
 
Returns the index of the first element equal to the target, or -1. Works on
unsorted data. O(n) comparisons in the worst case, 1 in the best; O(1) extra
space.
"""
 
import operator
from collections.abc import Callable, Sequence
from typing import Any
 
 
def linear_search(items: Sequence[Any], target: Any, equals: Callable[[Any, Any], bool] = operator.eq) -> int:
    for i in range(len(items)):
        if equals(items[i], target):
            return i  # the first match: stop early
    return -1  # compared every element

Tested on CPython 3.14.0 · examples/python/dsa_examples/linear_search.py

package dev.bekadan.dsa.searching;
 
import java.util.Objects;
import java.util.function.BiPredicate;
 
/**
 * Linear search with an early exit: the index of the first element equal to
 * the target, or -1. Works on unsorted data. O(n) comparisons in the worst
 * case, 1 in the best; O(1) extra space.
 */
public final class LinearSearch {
    private LinearSearch() {
    }
 
    public static <T> int indexOf(T[] items, T target) {
        return indexOf(items, target, Objects::equals);
    }
 
    public static <T> int indexOf(T[] items, T target, BiPredicate<? super T, ? super T> equals) {
        for (int i = 0; i < items.length; i++) {
            if (equals.test(items[i], target)) {
                return i; // the first match: stop early
            }
        }
        return -1; // compared every element
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/searching/LinearSearch.java

#pragma once
 
#include <cstddef>
#include <functional>
#include <span>
 
namespace bekadan::dsa {
 
// Linear search with an early exit: the index of the first element equal to
// the target, or -1. Works on unsorted data. O(n) comparisons in the worst
// case, 1 in the best; O(1) extra space. (std::find does the same with iterators.)
 
template <typename T, typename Equal = std::equal_to<>>
std::ptrdiff_t linear_search(std::span<const T> items, const T& target, Equal equal = {}) {
    for (std::size_t i = 0; i < items.size(); ++i) {
        if (equal(items[i], target)) {
            return static_cast<std::ptrdiff_t>(i);  // the first match: stop early
        }
    }
    return -1;  // compared every element
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/linear_search.hpp

References