Linear Search Visualization — Step by Step

Scans the array left to right, checking each element until the target is found or the end is reached.

SearchingbeginnerUpdated

// quick answer

Linear Search is a searching algorithm that runs in O(n) time on average with O(1) space. Scans the array left to right, checking each element until the target is found or the end is reached.

How Linear Search Works

Linear Search (or Sequential Search) is the simplest search algorithm. It checks every element in order until the target is found or the array ends. Works on unsorted arrays. O(n) time complexity, O(1) space. Best case is finding the target at index 0.

Linear Search Step by Step

One pass, left to right

Linear Search is the algorithm you would invent yourself: start at index 0 and check every element in turn until you find the target or run out of array. There is no preprocessing, no assumptions about order, and no extra memory — just a single loop and one comparison per element. That simplicity is the point. Every other search technique, from binary search to hash tables, is an answer to the question "how do we avoid looking at everything?" — and linear search is the baseline they are all measured against.

A concrete trace

Search [12, 5, 8, 21, 8] for the target 8. Index 0: compare 12 with 8 — no match, move on. Index 1: compare 5 with 8 — no match. Index 2: compare 8 with 8 — match, return index 2 after three comparisons. The search stops at the *first* occurrence: the second 8 at index 4 is never examined. In the visualizer you can watch exactly this — each cell lights up as it is visited, gets compared against the target, and the search halts the moment the match event fires.

Best, worst, and average cases

Where the target sits determines the cost. If it is at index 0, one comparison suffices — the O(1) best case. If it is the last element, or absent entirely, all n elements get checked — the O(n) worst case. For a target in a random position, you examine about n/2 elements on average, which is still O(n): constants are dropped in Big-O. The early exit matters in practice though — searches that usually hit near the front of the array behave far better than the worst case suggests.

Why it works on anything

Linear search demands almost nothing from its data. The array can be unsorted, contain duplicates, or hold objects with no natural ordering — you only need an equality check, and the check can be any condition at all ("first user whose age exceeds 30"), not just equality. It also works on structures without random access: scanning a linked list node by node *is* a linear search. This universality is why language built-ins like JavaScript's indexOf and find, or Python's in operator on lists, are linear searches under the hood.

The cost of no preparation

Compare the running totals against binary search on sorted data: at 1,000 elements, linear search averages around 500 comparisons while binary search needs about 10. At a million, it is roughly 500,000 versus 20. The lesson is not that linear search is bad — it is that preprocessing buys speed. Sorting enables binary search; hashing enables O(1) average lookups. When you search once, preparation costs more than it saves. When you search constantly, linear search is the wrong tool.

Time & Space Complexity

Best CaseAverage CaseWorst CaseSpace
O(1)O(n)O(n)O(1)

Linear Search Pseudocode

function linearSearch(arr, target):
  for i = 0 to n-1:
    if arr[i] == target:
      return i  // found
  return -1  // not found

Press play in the visualizer above to watch each line execute with live highlighting.

Linear SearchCode in JavaScript, Python & Java

JavaScript

function linearSearch(arr, target) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === target) {
      return i; // first matching index
    }
  }
  return -1; // reached the end without a match
}

// The same idea works for any condition, not just equality:
function findIndexBy(arr, predicate) {
  for (let i = 0; i < arr.length; i++) {
    if (predicate(arr[i])) {
      return i;
    }
  }
  return -1;
}

Python

def linear_search(arr, target):
    """Return the index of the first occurrence of target, or -1."""
    for i, value in enumerate(arr):
        if value == target:
            return i
    return -1


def linear_search_all(arr, target):
    """Return the indices of every occurrence of target."""
    return [i for i, value in enumerate(arr) if value == target]

Java

public class LinearSearch {
    public static int linearSearch(int[] arr, int target) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                return i; // first matching index
            }
        }
        return -1; // not found
    }

    public static void main(String[] args) {
        int[] data = {12, 5, 8, 21, 8};
        System.out.println(linearSearch(data, 8)); // prints 2
    }
}

When to Use Linear Search

  • Use it on small arrays (up to a few dozen elements) — the simple loop is fast, cache-friendly, and impossible to get wrong.
  • Use it for a one-off search of unsorted data: a single O(n) scan is cheaper than sorting at O(n log n) just to enable binary search.
  • Use it when the data structure only supports sequential access, such as a linked list or a stream you read once.
  • Use it when matching on an arbitrary condition rather than a key — predicates like "first item that is out of stock" cannot be binary-searched or hashed.
  • Do not use it for repeated lookups in a large collection — sort once and use binary search, or move the data into a hash table for O(1) average membership checks.
  • Do not use it when the data is already sorted and large; you would be ignoring free structure that makes searches exponentially cheaper.

Linear Search — Frequently Asked Questions

Does linear search work on unsorted data?

Yes — that is its defining advantage. Linear search makes no assumptions about order; it simply compares every element against the target until one matches. Binary search, by contrast, is only correct on sorted arrays. If your data is unsorted and you need exactly one search, a linear scan is the right choice, because sorting first would cost more than the scan itself.

Is linear search ever better than binary search?

Often, yes. On unsorted data a single linear scan beats sort-then-binary-search. On very small arrays the simple loop is competitive or faster because it has no per-step arithmetic and reads memory sequentially, which CPUs handle extremely well. And on sequential structures like linked lists, binary search cannot jump to the middle cheaply, so a linear scan is effectively the only option.

What is the time complexity of linear search?

Worst case O(n): the target is the last element or missing, so all n elements are checked. Best case O(1): the target sits at index 0. On average, a present target in a random position requires about n/2 comparisons, which is still classified as O(n) since Big-O ignores constant factors. Space complexity is O(1) — only a loop counter is needed.

Does linear search find the first or all occurrences of a value?

The standard version returns as soon as it finds a match, so it reports the first occurrence — the lowest matching index — and never examines later duplicates. If you need every occurrence, remove the early return and collect matching indices as you go; that variant always makes exactly n comparisons because it must scan the entire array.

Why is linear search O(1) in the best case?

Because of the early exit. The loop returns immediately when it finds a match, so if the target happens to be the very first element, the search performs a single comparison regardless of whether the array holds ten elements or ten million. Best-case analysis describes exactly this scenario — the minimum possible work — while worst and average cases describe the more typical costs.

Compare Linear Search

Related Algorithms

References & Further Reading