Linear search — find a key by scanning each item once

Linear search finds a key by reading items in order until one matches or the sequence ends. It fits an unordered sequence, a linked list, a short array, and a single query. It does not fit a long sorted array, or a collection that will be queried many times.


What problem it solves

The only legal probe is to read an item and compare it with the key. If the items may stand in any order, every item could be the match, and the match could be absent. Any algorithm that skips an item is wrong on the input that hides the key there. The scan follows.

If the key is at index i, the search performs i+1 comparisons. If it is absent, the search performs n. The worst case is Θ(n). Over a key equally likely to sit in any slot, and equally likely to be absent, the average is also Θ(n). Extra memory is a few pointers. That bound is optimal when no order is known.

A sentinel copy of the key, written in a spare slot past the last item, lets the loop stop on a match alone. One test then tells the sentinel from a real hit. The saving is the end-of-array test, not the key comparisons. Writing the sentinel over the last real item loses that item.

On a sorted random-access array the same scan is still correct and no longer optimal. Binary search then uses Θ(log n) comparisons. A hash table expects constant time after it is built. Both require preparation this one-shot scan does not.


Where it is used

Linear search is the lookup you already have when nothing has been indexed.

  • Python’s in and list.index walk a list from the front. JavaScript’s indexOf and includes do the same on an array.
  • A linked list has no cheaper probe. The node you skip might hold the key.
  • A database with no index on the column answers with a full table scan: the same walk, over the rows.
  • A short allow-list, menu, or config array is scanned even when it could be sorted. A few dozen comparisons beat the setup of a faster structure.
  • A file read line by line, looking for one string, is this scan over the lines.

Drop it when the data are sorted and random-access, or when the same unordered collection will answer enough queries to repay a hash table or a sort. Keep it for unsorted data, linked lists, one query, and arrays short enough that the log n of a binary search loses to a tight scan.


Working code

linear_search returns the index of the key, or None if the key is absent. linear_search_sentinel returns the same answer. It parks a copy of the key in a spare slot so the loop tests equality only. Both calls on [4, 2, 7, 3, 9] find 3 at index 3 and report that 8 is absent.

def linear_search(items, target):
    for i, item in enumerate(items):
        if item == target:
            return i
    return None


def linear_search_sentinel(items, target):
    a = list(items)
    a.append(target)
    i = 0
    while a[i] != target:
        i += 1
    if i == len(items):
        return None
    return i


items = [4, 2, 7, 3, 9]
assert linear_search(items, 3) == 3
assert linear_search(items, 8) is None
assert linear_search_sentinel(items, 3) == 3
assert linear_search_sentinel(items, 8) is None
print(linear_search(items, 3))

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 21 日。

One thought

Leave a Reply

Your email address will not be published. Required fields are marked *