4 / 7 · Basic
Sorting 2: merge sort and quicksort
Sorting a million values by comparing every pair takes about 500 billion comparisons; merge sort needs about 20 million.
Jump to the 11 practice questionsYou will learn
- Split a problem, solve the halves, combine them
- Follow merge sort and quicksort step by step
- Compare their cost in comparisons and memory
Before this: Sorting 1: bubble, selection and insertion sort
1Explain
Divide and conquer
The methods in the last unit work on the whole list at once and pay for it with about n² comparisons. The two methods in this unit use a different plan, called divide and conquer. Split the list into smaller parts, sort each part with the same method, and then combine the sorted parts. The splitting continues until a part has one value or none, and a list of one value is already sorted.
2Explain
Merging two sorted lists
Merge sort cuts the list in half, sorts the left half, sorts the right half, and merges the two sorted halves into one. The clever part is the merge. Two sorted lists can be combined by looking only at their front values. Compare the two fronts, write down the smaller one, and move past it. Repeat until one list is empty, then copy what is left of the other.
i and j point at the two fronts. Each round writes the smaller front into out and moves past it.
function merge(left, right) {const out = [];let i = 0, j = 0;while (i < left.length && j < right.length) {if (right[j] < left[i]) out.push(right[j++]);else out.push(left[i++]);}return out.concat(left.slice(i), right.slice(j));}console.log(merge([1, 4, 7], [2, 3, 8]));
[1,2,3,4,7,8]
3Problem
Comparisons in the merge
How many comparisons does it take to merge [1, 4, 7] and [2, 3, 8]?
Hint
1 vs 2, 4 vs 2, 4 vs 3, 4 vs 8, 7 vs 8; then 8 is copied.
Solution
Answer: 5
Merging compares the front values of the two lists and writes the smaller one. 1 vs 2, 4 vs 2, 4 vs 3, 4 vs 8, 7 vs 8. Then the left list is empty and 8 is copied without a comparison.
4Problem
One side runs out early
How many comparisons does it take to merge [1, 2, 3] and [4, 5, 6]?
Hint
After 1, 2 and 3 the left list is empty.
Solution
Answer: 3
1, 2 and 3 are each compared with 4 and written; then the left list is empty and 4, 5, 6 are copied.
5Explore
Merge sort on bars
Why is this fast? Picture the halving as levels. A list of 8 values splits into 2 lists of 4, then 4 lists of 2, then 8 lists of 1: three levels, because 8 can be halved 3 times. At each level, all the merges together touch each value once, so a level costs at most about n comparisons. With log₂ n levels the total is about n log₂ n. For a million values that is about 20 million comparisons, against about 500 billion for the pair-by-pair methods.
The bright part is being merged; each orange bar is one value written back. Small parts are merged first, then bigger ones.
6Problem
Levels of halving
A list of 16 values is halved until each part has one value. How many levels of halving are there?
Hint
16 → 8 → 4 → 2 → 1.
Solution
Answer: 4
Each halving cuts the part size in half, so count how many times 16 can be halved until it reaches 1: 16 → 8 → 4 → 2 → 1, four halvings, log₂ 16 = 4.
7Problem
A million values
Roughly how many comparisons does merge sort make on a million values?
Hint
About 20 levels, about a million comparisons per level.
Solution
Answer: about 20 million
Merge sort has about log₂ n levels of halving and about n comparisons per level, so n log₂ n = 1,000,000 × about 20 = about 20 million.
8Explain
The price: memory
The price is memory. Merging needs somewhere to write the output, so merge sort uses a second list as large as the input. Merge sort is also stable: values that compare equal keep their original order, because the merge takes from the left list when the fronts are equal. That matters when you sort a table by one column after another, for example by city and then by name.
9Problem
A second list
Which method needs a second list as large as the input?
Hint
Which method writes its output somewhere else?
Solution
Answer: Merge sort
Merging writes its output into a separate list.
10Explore
Quicksort: split around a pivot
The lab uses a common textbook version that takes the last value of each part as the pivot. On [5, 1, 4, 2, 8] the pivot 8 is compared with the four other values, all smaller, so 8 stays at the end. The next part [5, 1, 4, 2] uses pivot 2: only 1 is smaller, so after two swaps the list is [1, 2, 4, 5, 8]. One more comparison handles [4, 5].
Violet is the pivot, the last value of the part. Smaller values are swapped to the left, then the pivot drops into its final place.
11Problem
Where the pivot ends up
After partitioning, where is the pivot?
Hint
Everything on its left is smaller, everything on its right is not.
Solution
Answer: In its final sorted position
Every smaller value is to its left and every other value to its right, so it never moves again.
12Explore
A bad pivot
When the pivot lands near the middle, each split halves the problem and quicksort takes about n log₂ n comparisons, like merge sort. It also works inside the original list without a second copy. But a bad pivot hurts. If the list is already sorted and the pivot is always the last value, every split peels off just one value.
On a sorted list the last value is always the largest, so each part loses only one value: 4 + 3 + 2 + 1 = 10 comparisons.
13Problem
Quicksort on a sorted list
Quicksort with the last value as pivot runs on the already sorted list [1, 2, 3, 4, 5]. How many comparisons does it make?
Hint
Count the comparisons on the last page.
Solution
Answer: 10
Each pivot is the largest value of its part, so the parts shrink by one: 4 + 3 + 2 + 1 = 10.
14Explain
Side by side
Both methods have a known origin. Merge sort was proposed by John von Neumann in 1945, when the first stored-program computers were being designed. Quicksort came from Tony Hoare, a British student at Moscow State University in 1959. He was offered work on machine translation from Russian to English, and because the dictionary was kept on magnetic tape, the words of each sentence first had to be put into alphabetical order.
| Method | Comparisons | Extra memory |
|---|---|---|
| Insertion sort | usual about n²/4, worst about n²/2 | none; stable |
| Merge sort | about n log₂ n, always | a second list of n values; stable |
| Quicksort | usual about n log₂ n, worst about n²/2 (bad pivots) | little; usual versions not stable |
15Problem
Stable
Why is merge sort called stable?
Hint
Look at what the merge does when the two fronts are equal.
Solution
Answer: Equal values keep their original order
When the two fronts are equal, the merge takes from the left list first.
16Problem
Hoare's problem
What problem led Tony Hoare to quicksort?
Hint
He worked on machine translation in Moscow.
Solution
Answer: Sorting the words of a sentence for a dictionary on magnetic tape
He was working on Russian to English machine translation, and the words had to be in alphabetical order to look them up on tape.
17Practice
Finish merge
Finish merge so it prints [1,2,3,4,7,8].
[1,2,3,4,7,8]function merge(left, right) {
const out = [];
let i = 0, j = 0;
// While both lists have values, push the smaller front value.
return out.concat(left.slice(i), right.slice(j));
}
console.log(merge([1, 4, 7], [2, 3, 8]));
Hint
Push the smaller front and move past it with j++ or i++.
A solution
function merge(left, right) {
const out = [];
let i = 0, j = 0;
while (i < left.length && j < right.length) {
if (right[j] < left[i]) out.push(right[j++]);
else out.push(left[i++]);
}
return out.concat(left.slice(i), right.slice(j));
}
console.log(merge([1, 4, 7], [2, 3, 8]));18Practice
Write merge sort
Write mergeSort so the program prints [3,9,10,27,38,43,82].
[3,9,10,27,38,43,82]function merge(left, right) {
const out = [];
let i = 0, j = 0;
while (i < left.length && j < right.length) {
if (right[j] < left[i]) out.push(right[j++]);
else out.push(left[i++]);
}
return out.concat(left.slice(i), right.slice(j));
}
function mergeSort(a) {
// Base case, then split in half, sort both halves, merge.
return a;
}
console.log(mergeSort([38, 27, 43, 3, 9, 82, 10]));
Hint
Both halves must be sorted before they are merged: call mergeSort on each.
A solution
function merge(left, right) {
const out = [];
let i = 0, j = 0;
while (i < left.length && j < right.length) {
if (right[j] < left[i]) out.push(right[j++]);
else out.push(left[i++]);
}
return out.concat(left.slice(i), right.slice(j));
}
function mergeSort(a) {
if (a.length <= 1) return a;
const mid = Math.floor(a.length / 2);
return merge(mergeSort(a.slice(0, mid)), mergeSort(a.slice(mid)));
}
console.log(mergeSort([38, 27, 43, 3, 9, 82, 10]));19Explain
Common mistakes
function mergeSort(a) {
const mid = Math.floor(a.length / 2);
return mergeSort(a.slice(0, mid)).concat(mergeSort(a.slice(mid)));
}
console.log(mergeSort([3, 1, 2]));RangeError: Maximum call stack size exceeded (line 3)
- The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
- After the colon: what went wrong, usually with the name involved.
- The line number shows where the program stopped. A SyntaxError stops it before any line runs.
Without the base case (a list of one value is already sorted) the calls never stop.
20
Summary
- Divide and conquer: split, solve the parts, combine.
- Merge sort: about n log₂ n comparisons always, needs extra memory, stable.
- Quicksort: partition around a pivot; fast on average, about n²/2 with bad pivots.
- A million values: about 20 million comparisons instead of 500 billion.
- No comparison sort can beat about n log₂ n in the worst case.