Chuyển tới nội dung chính
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

Câu hỏi thường gặp

Linear search là gì?

Linear search (tìm kiếm tuần tự) kiểm tra lần lượt từng phần tử của danh sách theo thứ tự cho đến khi tìm thấy giá trị đích hoặc quét hết danh sách.

Độ phức tạp thời gian của linear search là gì?

O(n) trong trường hợp trung bình và xấu nhất — có thể phải kiểm tra mọi phần tử. Trường hợp tốt nhất là O(1) khi giá trị đích là phần tử đầu tiên.

Linear search có cần dữ liệu đã sắp xếp không?

Không. Linear search hoạt động trên mọi mảng, dù đã sắp xếp hay chưa. Sự linh hoạt này chính là lợi thế chính của nó so với binary search.

Khi nào nên dùng linear search?

Với tập dữ liệu nhỏ hoặc chưa sắp xếp, hoặc khi dữ liệu chỉ được tìm kiếm một lần (sắp xếp trước sẽ tốn kém hơn một lượt quét tuyến tính duy nhất).