メインコンテンツへスキップ
Z

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

よくある質問

線形探索とは何ですか?

線形探索(シーケンシャルサーチ)は、リストの要素を先頭から順に1つずつ調べ、ターゲット値が見つかるかリストの末尾に達するまで確認を続けるアルゴリズムです。

線形探索の時間計算量はどれくらいですか?

平均・最悪ケースともにO(n)です。すべての要素を調べる必要がある場合があるためです。ターゲット値が先頭要素であればO(1)となる最良ケースもあります。

線形探索を行うにはデータをソートしておく必要がありますか?

いいえ、必要ありません。線形探索はソート済みかどうかにかかわらず、あらゆる配列に対して機能します。この柔軟性こそが、binary search(二分探索)に対する線形探索の主な利点です。

線形探索はどんな場面で使うべきですか?

データセットが小さい場合や未ソートの場合、またはデータを一度しか探索しない場合に適しています(そうした場合、事前にソートするコストの方が、1回の線形走査より高くつくためです)。