Searching · O(n)

Linear search

Scan left to right until the first match, counting comparisons and bounds checks.

The full explanation, derivation and practice are in the lesson Linear search and its preconditions.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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