← Algorithms · Lesson 4/11
Merge sort
▶ Watch it as a video: one minute with LeIA
Divide and conquer
Bubble, insertion and selection sort compare almost everything against everything: O(n²). Merge sort brings that down by splitting the problem. An array with a single number is already sorted; a bigger one is split into two halves, each half is sorted with the same function, and then the two sorted halves are merged.
Merging is easy because both already come in order: compare their heads and take the smaller one, like combining two face-up piles of cards. In the program, i and j are the heads of a and b, and k is the slot of v to write next.
$ node leccion.js
Press RUN (or Ctrl+Enter).
What to look at
slicemakes copies: the halvesaandbare sorted separately and the result is written back intov.- When
aruns out,a[i]isundefinedanda[i] <= b[j]isfalse: it takes fromb. Whenbruns out,j >= b.lengthtakes fromawithout comparing.
The whole lesson on one page
Divide and conquer
Bubble, insertion and selection sort compare almost everything against everything: O(n²). Merge sort brings that down by splitting the problem. An array with a single number is already sorted; a bigger one is split into two halves, each half is sorted with the same function, and then the two sorted halves are merged.
Merging is easy because both already come in order: compare their heads and take the smaller one, like combining two face-up piles of cards. In the program, i and j are the heads of a and b, and k is the slot of v to write next.
function mezcla(v) {
if (v.length < 2) return v;
const m = Math.floor(v.length / 2);
const a = mezcla(v.slice(0, m));
const b = mezcla(v.slice(m));
let i = 0, j = 0;
for (let k = 0; k < v.length; k++) {
if (j >= b.length || a[i] <= b[j])
v[k] = a[i++];
else v[k] = b[j++];
}
return v;
}
const lista = [5, 2, 8, 3, 7, 1, 6, 4];
console.log(mezcla(lista));
slicemakes copies: the halvesaandbare sorted separately and the result is written back intov.- When
aruns out,a[i]isundefinedanda[i] <= b[j]isfalse: it takes fromb. Whenbruns out,j >= b.lengthtakes fromawithout comparing.
Merge by merge
The same function, printing every merge and counting the comparisons between two numbers (the ones made while both halves still have heads).
let comparaciones = 0;
function mezcla(v) {
if (v.length < 2) return v;
const m = Math.floor(v.length / 2);
const a = mezcla(v.slice(0, m));
const b = mezcla(v.slice(m));
let i = 0, j = 0;
for (let k = 0; k < v.length; k++) {
if (i < a.length && j < b.length) comparaciones++;
if (j >= b.length || a[i] <= b[j]) v[k] = a[i++];
else v[k] = b[j++];
}
console.log(a.join(" "), "+", b.join(" "), "→", v.join(" "));
return v;
}
mezcla([5, 2, 8, 3, 7, 1, 6, 4]);
console.log("comparisons:", comparaciones);
- Seven merges: four of pairs, two of four numbers and one of eight.
- 17 comparisons, against bubble sort's 28.
Why n log n
Count by levels. Halving over and over gives about log₂ n levels (3 with 8 numbers). On each level, across all the merges, every number is written once: n steps per level. Total: n log n.
With 1,000 random numbers that's about 8,700 comparisons, against bubble sort's 499,500. The price: the slice copies take extra memory, as much as the array. JavaScript's sort belongs to this family.
let c = 0;
function mezcla(v) {
if (v.length < 2) return v;
const m = Math.floor(v.length / 2);
const a = mezcla(v.slice(0, m));
const b = mezcla(v.slice(m));
let i = 0, j = 0;
for (let k = 0; k < v.length; k++) {
if (i < a.length && j < b.length) c++;
if (j >= b.length || a[i] <= b[j]) v[k] = a[i++];
else v[k] = b[j++];
}
return v;
}
// random numbers: always the same ones, because the seed is fixed
function alAzar(n) {
let s = 42;
return Array.from({ length: n }, () => (s = s * 16807 % 2147483647) % 1000);
}
for (const n of [100, 1000]) {
c = 0;
mezcla(alAzar(n));
console.log(n, "numbers:", c, "comparisons; bubble sort:", n * (n - 1) / 2);
}
- With 100 numbers, 542 comparisons against 4,950; with 1,000, 8,714 against 499,500.
- For every 10 times more data, bubble sort does 100 times the work; merge sort, about 16.