Saltar al contenido principal
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

Preguntas frecuentes

¿Qué es linear search?

Linear search (búsqueda lineal) revisa cada elemento de una lista en orden, uno por uno, hasta encontrar el valor objetivo o llegar al final de la lista.

¿Cuál es la complejidad temporal de linear search?

O(n) en el caso promedio y en el peor caso — puede ser necesario revisar todos los elementos. El mejor caso es O(1), cuando el valor objetivo es el primer elemento.

¿Linear search necesita que los datos estén ordenados?

No. Linear search funciona con cualquier array, esté ordenado o no. Esa flexibilidad es su principal ventaja frente a binary search.

¿Cuándo conviene usar linear search?

Con conjuntos de datos pequeños o sin ordenar, o cuando los datos solo se van a buscar una vez (ordenarlos antes saldría más caro que un único recorrido lineal).