← Algorithms · Lesson 6/11
Binary search
▶ Watch it as a video: one minute with LeIA
Searching: one by one
To find out whether a number is in a list, the most direct way is to look at them one by one from the start until you find it or the list runs out. That's linear search, and it's what JavaScript's indexOf and includes do under the hood.
It works on any list, sorted or not. The problem is size: if what you want is at the end (or isn't there), you have to look at all n. It's O(n): with a million items, a million looks.
$ node leccion.js
Press RUN (or Ctrl+Enter).
What to look at
- 63 is in slot 10: to get there, it looked at 11 numbers.
- 60 isn't there: it returns −1 after looking at all 16.
-1is the usual way to say "not found", since no slot is negative.
The whole lesson on one page
Searching: one by one
To find out whether a number is in a list, the most direct way is to look at them one by one from the start until you find it or the list runs out. That's linear search, and it's what JavaScript's indexOf and includes do under the hood.
It works on any list, sorted or not. The problem is size: if what you want is at the end (or isn't there), you have to look at all n. It's O(n): with a million items, a million looks.
function lineal(a, x) {
for (let i = 0; i < a.length; i++) {
if (a[i] === x) return i;
}
return -1;
}
const lista = [4, 9, 13, 18, 25, 31, 37, 42, 50, 56, 63, 71, 77, 84, 90, 97];
console.log(lineal(lista, 63));
console.log(lineal(lista, 60));
// indexOf does the same
console.log(lista.indexOf(63));
- 63 is in slot 10: to get there, it looked at 11 numbers.
- 60 isn't there: it returns −1 after looking at all 16.
-1is the usual way to say "not found", since no slot is negative.
The idea: look in the middle
If someone thinks of a number from 1 to 100 and answers "higher" or "lower", you don't ask 1, 2, 3…: you say 50, and one answer throws away half. That way you can guess any of them in 7 questions or fewer. That's binary search.
A sorted list works the same way. Two indices, izq (left) and der (right), mark the range where it can still be. You look at the middle one: if it's the one, done; if it's smaller than x, everything to its left is smaller too and can go (izq = medio + 1); if it's bigger, everything to its right goes (der = medio - 1). When izq passes der, the range is empty: it's not there.
function buscar(a, x) {
let izq = 0, der = a.length - 1;
while (izq <= der) {
const medio = Math.floor((izq + der) / 2);
if (a[medio] === x) return medio;
if (a[medio] < x) izq = medio + 1;
else der = medio - 1;
}
return -1;
}
const lista = [4, 9, 13, 18, 25, 31, 37, 42, 50, 56, 63, 71, 77, 84, 90, 97];
console.log(buscar(lista, 63));
console.log(buscar(lista, 60));
- It returns the same as linear search: 10 for 63 and −1 for 60.
Math.floorrounds down: withizq = 0andder = 15, the middle one is 7.
Look by look
The same function, now saying what it looks at on each turn. Searching for 63: the middle one is 42 (too small: the left goes), then 71 (too big: the right goes), 56 (too small) and 63. Four looks, against 11 one by one.
With 60, which isn't there, it's also four: after looking at 63, der ends up before izq and the loop is over.
function buscar(a, x) {
let izq = 0, der = a.length - 1;
let miradas = 0;
while (izq <= der) {
const medio = Math.floor((izq + der) / 2);
miradas++;
console.log("look", miradas, "| izq", izq, "der", der, "| medio", medio, "→", a[medio]);
if (a[medio] === x) return medio;
if (a[medio] < x) izq = medio + 1;
else der = medio - 1;
}
return -1;
}
const lista = [4, 9, 13, 18, 25, 31, 37, 42, 50, 56, 63, 71, 77, 84, 90, 97];
console.log("63 is at", buscar(lista, 63));
console.log("60 is at", buscar(lista, 60));
- Watch
izqandderclose in: from 0–15 to 8–15, 8–10, 10–10. - Change the number you search for: none of the 16 needs more than 5 looks.
Why O(log n)
Each look leaves half of what there was: with 16, 8 are left, then 4, 2, 1. The looks are the number of times you can halve n until nothing is left: about log₂ n, and in the worst case exactly ⌊log₂ n⌋ + 1.
That grows very slowly: with twice the data, you need just one more look. 2¹⁰ is 1,024, so a thousand numbers take 10 looks; 2²⁰ is over a million, so a million take 20. That's why it's O(log n), and why searching something sorted is so fast.
// The worst case: search for one bigger than all,
// so it always goes right
function peorCaso(n) {
const a = Array.from({ length: n }, (_, i) => i);
let izq = 0, der = n - 1, miradas = 0;
while (izq <= der) {
const medio = Math.floor((izq + der) / 2);
miradas++;
if (a[medio] < n) izq = medio + 1;
else der = medio - 1;
}
return miradas;
}
for (const n of [16, 100, 1000, 2000, 1000000]) {
console.log(n, "→ one by one:", n, "| binary:", peorCaso(n));
}
- 16 → 5, 100 → 7, 1,000 → 10, 2,000 → 11, 1,000,000 → 20.
- Going from 1,000 to 2,000 items, linear search does twice the work; binary search, one more look.
Careful: it has to be sorted
Throwing away a half only works if you know everything on that side is smaller (or bigger). Order guarantees that. On a shuffled list, binary search gets it wrong without warning: it says −1 even though the number is there.
Sorting first costs O(n log n), more than one linear search. It pays off when you'll search the same list many times: sort it once and every search after that costs O(log n). That's how a paper dictionary, a database index or your phone's contact list work.
function buscar(a, x) {
let izq = 0, der = a.length - 1;
while (izq <= der) {
const medio = Math.floor((izq + der) / 2);
if (a[medio] === x) return medio;
if (a[medio] < x) izq = medio + 1;
else der = medio - 1;
}
return -1;
}
const revuelta = [42, 9, 77, 4, 63, 18, 90, 31];
console.log("shuffled:", buscar(revuelta, 63));
const ordenada = [...revuelta].sort((a, b) => a - b);
console.log(ordenada);
console.log("sorted:", buscar(ordenada, 63));
- Shuffled: −1, and 63 is right there in slot 4! It looked at 4 (too small), 18 (too small) and 90 (too big), and ran out of range.
- Sorted: it finds it in slot 5.