Search algorithms find target values in collections, trees, graphs, or text while minimizing work. Choosing the right search approach depends on data ordering, data shape, and whether you need worst-case guarantees or best average speed.

Concrete example: in a sorted list of product ids, Binary Search gives fast lookups with logarithmic time. In graph traversal, BFS finds the shortest path by edge count in unweighted graphs. In text processing, KMP and Rabin Karp avoid naive full rescans.

Diagram

flowchart TD
  A[Need to find target] --> B{Data is sorted array}
  B -->|Yes| C{Length known and random access cheap}
  C -->|Yes| C1[Binary Search]
  C -->|Unbounded or target near the front| C2[Exponential Search]
  C -->|Backward seeks are expensive| C3[Jump Search]
  B -->|No| D{Data is graph}
  D -->|Yes| E[DFS BFS]
  D -->|No| F{Data is text pattern}
  F -->|One pattern| G[KMP or Boyer Moore or Z Algorithm]
  F -->|Many patterns at once| G2[Aho Corasick]
  F -->|No| H{Optimising a unimodal function}
  H -->|Yes| I[Ternary Search]
  H -->|No| J[Use linear scan or indexing structure]

Algorithm Selection

Searching an array

Data shapeAlgorithmTimePrecondition
Unsorted array, linked list, or one-pass streamLinear SearchO(n)None; needs no index or random access
Sorted arrayBinary SearchO(log n)Sorted, random access
Sorted, unbounded length or target near frontExponential SearchO(log i) for target at index iSorted
Sorted, uniformly distributed keysInterpolation SearchO(log log n) avg, O(n) worstSorted and near-uniform numeric distribution
Sorted, forward-only / costly backward seeksJump SearchO(√n)Sorted
Unimodal function, not an arrayTernary SearchO(log n) probesStrict unimodality

Binary Search also serves range and insertion-point queries — lower-bound / upper-bound, first/last match — because it keeps the data in sorted order rather than building a separate index.

Searching text

Text/pattern matching is its own sub-family — see String Matching for the full comparison.

Data shapeAlgorithmTimePrecondition
Text + one patternKMPO(n + m)
Text + one pattern, large alphabetBoyer-MooreO(n/m) best, O(n) with GalilSublinear in practice; powers grep
Text + one pattern, prefix-structure problemsZ-AlgorithmO(n + m)
Text + many patterns at onceAho-CorasickO(n + matches) after buildBuild cost is sum of pattern lengths
Text + rolling / multi-pattern hashingRabin–KarpO(n + m) avgGood hash to avoid collisions

Searching a graph

Data shapeAlgorithmTimePrecondition
Graph (unweighted) DFSO(V + E)
Graph (weighted)See Graph AlgorithmsDijkstra, A* Search, Bellman-Ford

Questions

References

7 items under this folder.