Algorithm · Searching · O(n)

Linear search

Check each element from the start until one matches. O(n), no preconditions, and the right choice for small or unsorted data.

The full derivation, edge cases and exercises are in the lesson From problem to algorithm: inputs, outputs and constraints. Open it full width in the playground.

On this page
  1. The idea
  2. Steps
  3. Invariants
  4. Complexity
  5. When to use it
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

Linear search makes no assumption about the order of the data, so the only way to be sure a value is absent is to look at every element. It stops at the first match, which also makes it the natural way to find a first occurrence.

Steps

  1. Start at index 0.
  2. If the element equals the target, return its index.
  3. Otherwise move to the next index; past the end, return “not found”.

Invariants

What holds at every step; the correctness argument rests on these.

  • Before checking index i, none of the elements at 0 … i − 1 equals the target.

Complexity

Linear search complexity
CaseTimeExtra spaceNotes
Best caseO(1)O(1)The first element matches.
Worst caseO(n)O(1)The target is last or missing.
Average (target present, uniform position)≈ n / 2 comparisonsO(1)

When to use it

Use it when

  • The data is unsorted, small, or searched only once (sorting first costs O(n log n)).
  • You need the first element that satisfies an arbitrary condition, not just equality.

Avoid it when

  • You search the same sorted data many times: binary search is O(log n).
  • You look up by key repeatedly: build a hash set or map once.

Step through it

The interactive lab for linear search: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

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

Learn more

Data structures it uses

Comparisons

  • Linear search vs binary search· A left-to-right scan against halving the range, on one sorted array. The scan wins only when the target sits near the front.

Problems, patterns and exercises

References