← Algorithms · Lesson 1/11
Bubble sort
▶ Watch it as a video: one minute with LeIA
Sorting: the problem
Sorting means putting data in order, smallest to largest (or the other way around). Computers do it all the time: a game's top 10, a store's prices, the contacts on your phone. And it's almost always the first step toward something else: a sorted list can be searched with binary search, duplicates end up side by side, and the minimum and maximum sit at the ends.
There are many sorting algorithms. The first one people learn is bubble sort: it isn't the fastest, but it fits in one sentence and thirteen lines.
$ node leccion.js
Press RUN (or Ctrl+Enter).
What to look at
- Once sorted, the minimum and the maximum are one O(1) read each.
- The last line gives
[ 1, 10, 9 ]: without the function,sortcompares characters. A classic bug. - In this lesson you'll write your own sort, without
sort.
The whole lesson on one page
Sorting: the problem
Sorting means putting data in order, smallest to largest (or the other way around). Computers do it all the time: a game's top 10, a store's prices, the contacts on your phone. And it's almost always the first step toward something else: a sorted list can be searched with binary search, duplicates end up side by side, and the minimum and maximum sit at the ends.
There are many sorting algorithms. The first one people learn is bubble sort: it isn't the fastest, but it fits in one sentence and thirteen lines.
const puntos = [5, 2, 8, 3, 7, 1, 6, 4];
// sort comes with JavaScript;
// (a, b) => a - b compares numbers
const orden = [...puntos];
orden.sort((a, b) => a - b);
console.log(orden);
console.log("min:", orden[0]);
console.log("max:", orden.at(-1));
// Without it, it compares text:
// "10" comes before "9"
console.log([10, 9, 1].sort());
- Once sorted, the minimum and the maximum are one O(1) read each.
- The last line gives
[ 1, 10, 9 ]: without the function,sortcompares characters. A classic bug. - In this lesson you'll write your own sort, without
sort.
The idea: neighbors out of order
The idea fits in one sentence: walk the list comparing each pair of neighbors and, if they're out of order, swap them.
When a full walk (a pass) ends, the largest number has already reached the end: every comparison carried it along, like a bubble rising. Hence the name. The second pass takes the second largest to its place, and so on until everything is in order.
In the program, i counts the passes and j walks the pairs a[j] and a[j + 1]. Each pass checks one pair fewer than the one before, because the last ones are already in place.
function burbuja(a) {
const n = a.length;
for (let i = 1; i < n; i++) {
for (let j = 0; j < n - i; j++) {
if (a[j] > a[j + 1]) {
const t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
return a;
}
const lista = [5, 2, 8, 3, 7, 1, 6, 4];
console.log(burbuja(lista));
- The swap uses a helper variable
t: if you doa[j] = a[j + 1]first, the value ofa[j]is lost. - The function sorts the array in place (it changes the one you pass in, without making another) and also returns it.
Pass by pass
To see what it does, here's the same function with three additions: it prints the array after each pass and counts the comparisons (how many times the if runs) and the swaps (how many times two trade places).
function burbuja(a) {
const n = a.length;
let comparaciones = 0;
let intercambios = 0;
for (let i = 1; i < n; i++) {
for (let j = 0; j < n - i; j++) {
comparaciones++;
if (a[j] > a[j + 1]) {
const t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
intercambios++;
}
}
console.log("pass", i + ":", ...a);
}
console.log("comparisons:", comparaciones);
console.log("swaps:", intercambios);
return a;
}
burbuja([5, 2, 8, 3, 7, 1, 6, 4]);
- Look at the end of each line: after pass 1 the 8 is already last; after pass 2, the 7; after pass 3, the 6.
- It's sorted from pass 5 on, but passes 6 and 7 run anyway.
- There are 7 + 6 + 5 + 4 + 3 + 2 + 1 = 28 comparisons, however the numbers come in. The swaps depend on how shuffled the list is: 15 here.
Why it's slow: O(n²)
With n numbers, the first pass makes n - 1 comparisons, the second n - 2, and so on down to 1. That's n(n - 1)/2 in total: 28 with 8 numbers; 4,950 with 100; almost half a million with 1,000.
That grows like n²: twice the data, four times the work. That's why bubble sort is O(n²). With a few dozen items you won't notice; with a million it would take half a trillion comparisons. The sorts that ship with languages, like JavaScript's sort, are O(n log n): merge sort's family.
// Bubble sort's comparisons,
// counted without sorting anything
function comparaciones(n) {
let c = 0;
for (let i = 1; i < n; i++) {
for (let j = 0; j < n - i; j++) c++;
}
return c;
}
for (const n of [8, 100, 1000, 2000]) {
console.log(n, "→", comparaciones(n));
}
console.log("formula for 2000:", 2000 * 1999 / 2);
- The loop agrees with the formula n(n - 1)/2: the last line works it out for 2,000.
- Going from 1,000 to 2,000 numbers, comparisons go from 499,500 to 1,999,000: four times as many for twice the data.
An improvement: stop when it's done
In the example, passes 6 and 7 changed nothing. The usual improvement is to keep a flag: if a whole pass made no swap at all, the list is already sorted and you can stop.
With a list that comes in sorted, one pass is enough: O(n) in the best case. In the worst case, a reversed list, it's still O(n²). Also, here the swap fits on one line with destructuring: [a[j], a[j + 1]] = [a[j + 1], a[j]] does the same as the three lines with t.
function conBandera(a) {
const n = a.length;
let comparaciones = 0;
for (let i = 1; i < n; i++) {
let cambio = false;
for (let j = 0; j < n - i; j++) {
comparaciones++;
if (a[j] > a[j + 1]) {
[a[j], a[j + 1]] = [a[j + 1], a[j]];
cambio = true;
}
}
if (!cambio) break; // done
}
return comparaciones;
}
const revuelta = [5, 2, 8, 3, 7, 1, 6, 4];
const ordenada = [1, 2, 3, 4, 5, 6, 7, 8];
const alReves = [8, 7, 6, 5, 4, 3, 2, 1];
console.log("shuffled:", conBandera(revuelta));
console.log("sorted: ", conBandera(ordenada));
console.log("reversed:", conBandera(alReves));
- Shuffled: 27 instead of 28. Pass 6 changed nothing, so it stopped there and skipped pass 7.
- Already sorted: 7, a single pass.
- Reversed: 28, the worst case, because every comparison ends in a swap.