en/docs/chapter_searching/searching_algorithm_revisited.md
<u>Searching algorithms</u> are used to search for one or a group of elements that meet specific conditions in data structures (such as arrays, linked lists, trees, or graphs).
Searching algorithms can be divided into the following two categories based on their implementation approach:
It's not hard to see that these topics have all been covered in previous chapters, so searching algorithms are not unfamiliar to us. In this section, we will approach from a more systematic perspective and re-examine searching algorithms.
Brute-force search locates target elements by traversing each element of the data structure.
The advantage of brute-force search is that it is simple and has good generality, requiring no data preprocessing or additional data structures.
However, the time complexity of such algorithms is $O(n)$, where $n$ is the number of elements, so performance is poor when dealing with large amounts of data.
Adaptive search utilizes the unique properties of data (such as orderliness) to optimize the search process, thereby locating target elements more efficiently.
The advantage of such algorithms is high efficiency, with time complexity reaching $O(\log n)$ or even $O(1)$.
However, using these algorithms often requires data preprocessing. For example, binary search requires pre-sorting the array, while hash-based search and tree search both require additional data structures, and maintaining these data structures also requires extra time and space overhead.
!!! tip
Adaptive search algorithms are often called lookup algorithms, **mainly used to quickly retrieve target elements in specific data structures**.
Given a dataset of size $n$, we can use linear search, binary search, tree search, hash-based search, and other methods to search for the target element. The working principles of each method are shown in the figure below.
The operational efficiency and characteristics of the above methods are as follows:
<p align="center"> Table <id> Comparison of search algorithm efficiency </p>| Linear search | Binary search | Tree search | Hash-based search | |
|---|---|---|---|---|
| Search element | $O(n)$ | $O(\log n)$ | $O(\log n)$ | $O(1)$ |
| Insert element | $O(1)$ | $O(n)$ | $O(\log n)$ | $O(1)$ |
| Delete element | $O(n)$ | $O(n)$ | $O(\log n)$ | $O(1)$ |
| Extra space | $O(1)$ | $O(1)$ | $O(n)$ | $O(n)$ |
| Data preprocessing | / | Sorting $O(n \log n)$ | Tree building $O(n \log n)$ | Hash table building $O(n)$ |
| Data ordered | Unordered | Ordered | Ordered | Unordered |
The choice of search algorithm also depends on data volume, search performance requirements, data query and update frequency, etc.
Linear search
Binary search
Hash-based search
Tree search