liveBook · Manning

Linear search

As explained in Grokking Data Structures

Linear search examines the elements of a sequence one by one, typically from one end to the other, until the target is found or the sequence is exhausted.

Linear search checks sequence elements one at a time, usually from the beginning, and stops when it finds the target or reaches the end. It works for arrays and linked lists, though its straightforward scan can require visiting every element. section 3.6 section 6.8

Its behavior changes slightly with the data structure:

  • In a sorted array, stop an unsuccessful search when the current element is larger than the target; later elements cannot match. section 3.6
  • In a linked list, traverse node by node until finding the value or reaching the end; additional links in a doubly linked list usually do not improve this search. section 6.18
  • The worst-case running time is O(n), although a successful search may return after one iteration and an average successful search may inspect about half the elements. section 4.14
  • Binary search can be faster on arrays because indexed middle-element access lets it discard half the remaining elements, an advantage linked lists generally lack. section 6.13

A sorted-array scan

Searching for 8 in a sorted array that reaches 9 requires checking every earlier element and then stopping at 9: the larger value proves that 8 is absent. The implementation returns the matching index or None. section 3.6

def linear_search(self, target):
    for i in range(self._size):
        if self._array[i] == target:
            return i
        elif self._array[i] > target:
            return None
    return None

View a compact implementation that scans an array, returns the matching index, and stops early when sorted order rules out the target. section 3.6

How Grokking Data Structures covers it

How deep it goes
Explains scan behavior, sorted-array early termination, linked-list constraints, implementations, and O(n) analysis before contrasting binary search.
Examples
Uses sorted-array searches for targets 8 and 9, plus array and linked-list search implementations.
What it assumes
Assumes basic arrays and linked lists, while introducing search control flow and linear running-time analysis.
What you can do after
Build it from scratch by scanning arrays or linked lists, returning a match appropriately, and recognizing O(n) performance.
How it connects
Connects linear search with sorted arrays, linked lists, binary search, and Big-O notation.

Also explained in

Compare how 5 books explain linear search →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Data Structures. The section links point to the parts of the book it draws on.