Searching Algorithms
Linear vs binary search — when sorted data pays off
Searching asks a simple question — is this value here, and where? — but the answer’s cost depends entirely on structure.
Linear search
Linear search checks each element in turn until it finds the target or reaches the end. It runs in O(n) and works on any list — sorted or not, array or linked list. For small or unsorted data it is often the right, simplest choice.
Binary search
Binary search repeatedly halves a sorted range: compare the middle element, then discard the half that cannot contain the target. It reaches the answer in O(log n) — about 20 comparisons for a million items versus up to a million for linear search. The catch is the precondition: the data must already be sorted, so binary search pairs naturally with the sorting algorithms above.
The visualizers below show the difference dramatically — linear search crawling element by element, versus binary search leaping to the midpoint and throwing away half the data each step.
Try it interactively
常见问题
什么是顺序查找?
顺序查找(线性查找)是按顺序逐一检查列表中的每个元素,直到找到目标值或遍历完整个列表为止的一种查找算法。
顺序查找的时间复杂度是多少?
平均情况和最坏情况下均为 O(n)——可能需要检查每一个元素。最好情况下为 O(1),即目标值恰好是第一个元素。
顺序查找需要数据已排序吗?
不需要。顺序查找可以在任意数组上运行,无论是否已排序。这种灵活性正是它相较于二分查找的主要优势。
什么时候应该使用顺序查找?
适用于数据量较小、未排序,或数据只需查找一次的场景(此时提前排序的开销会比一次线性扫描更大)。