# Search algorithms revisited A search algorithm finds one or more elements that satisfy specified conditions in a data structure, such as an array, linked list, tree, or graph. Search algorithms fall into two categories according to their approach. - **Locate the target by traversing the data structure**, as in traversals of arrays, linked lists, trees, and graphs. - **Find elements efficiently by using the organization of the data or prior information about it**, as in binary search, hash lookup, and binary search tree lookup. These ideas have all appeared in earlier chapters, so search algorithms are already familiar to us. In this section, we revisit them from a more systematic perspective. ## Brute-force search Brute-force search locates a target by visiting the elements of a data structure one by one. - “Linear search” applies to linear data structures such as arrays and linked lists. Starting at one end, it visits elements in sequence until it finds the target or reaches the other end without finding it. - “Breadth-first search” and “depth-first search” are two strategies for traversing graphs and trees. Breadth-first search starts at an initial node and searches level by level, visiting nearby nodes before more distant ones. Depth-first search follows a path as far as possible, then backtracks and tries other paths until the whole structure has been traversed. Brute-force search is simple and broadly applicable. **It requires neither preprocessing the data nor building an additional data structure**. However, **these algorithms take $O(n)$ time**, where $n$ is the number of elements, so they perform poorly on large datasets. ## Adaptive search Adaptive search uses properties of the data, such as its ordering, to optimize the search process and locate the target more efficiently. - “Binary search” uses sorted data to search efficiently and applies only to arrays. - “Hash lookup” uses a hash table to map lookup keys to target data as key-value pairs. - “Tree search” uses comparisons of node values in a particular tree structure, such as a binary search tree, to rule out nodes quickly and locate the target. These algorithms are efficient, **achieving time complexities of $O(\log n)$ or even $O(1)$**. However, **they often require preprocessing the data**. Binary search requires sorting the array in advance; hash lookup and tree search require additional data structures, whose maintenance also costs time and space. !!! tip Adaptive search algorithms are often called lookup algorithms. **Their main purpose is to retrieve target elements quickly from specific data structures**. ## Choosing a search method Given a dataset of size $n$, we can find a target using linear search, binary search, tree search, hash lookup, and other methods. The figure below illustrates how these methods work.  The table below compares their efficiency and properties.
Table