edubun
English
1 / 20

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 questions

You 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.

  1. function merge(left, right) {
  2. const out = [];
  3. let i = 0, j = 0;
  4. while (i < left.length && j < right.length) {
  5. if (right[j] < left[i]) out.push(right[j++]);
  6. else out.push(left[i++]);
  7. }
  8. return out.concat(left.slice(i), right.slice(j));
  9. }
  10. console.log(merge([1, 4, 7], [2, 3, 8]));
Variables
Output
[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.

0123456

Start: compare and swap until the list is in order.

Comparisons 0Writes 0

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.

01234

Start: compare and swap until the list is in order.

Comparisons 0Swaps 0

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.

01234

Start: compare and swap until the list is in order.

Comparisons 0Swaps 0

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.

MethodComparisonsExtra memory
Insertion sortusual about n²/4, worst about n²/2none; stable
Merge sortabout n log₂ n, alwaysa second list of n values; stable
Quicksortusual 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].

Expected output
[1,2,3,4,7,8]
Your code
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].

Expected output
[3,9,10,27,38,43,82]
Your code
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]));
Error message
RangeError: Maximum call stack size exceeded (line 3)
  1. The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
  2. After the colon: what went wrong, usually with the name involved.
  3. 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.

Next unitHow fast? Big O notation
Full text · The whole lesson as one text

Split the problem, solve the halves

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. Because the method calls itself on smaller lists, it is recursive (unit 6 looks at recursion in detail).

Merge sort: the work is in the merging

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. Merging [1, 4, 7] and [2, 3, 8] goes 1 (1 vs 2), 2 (4 vs 2), 3 (4 vs 3), 4 (4 vs 8) and 7 (7 vs 8). Then 8 is copied. That is 5 comparisons for 6 values. A merge of two lists with n values in total never needs more than n − 1 comparisons.

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;          // already sorted
  const mid = Math.floor(a.length / 2);
  return merge(mergeSort(a.slice(0, mid)), mergeSort(a.slice(mid)));
}

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. Split as [38, 27, 43, 3] and [9, 82, 10], as in the lab, the list [38, 27, 43, 3, 9, 82, 10] takes 14 comparisons. The code above splits it 3 and 4 and takes 13.

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.

Merge sort shades the part being merged; quicksort marks the pivot in violet. Raise the number of values to 40 and compare the counters with insertion sort.

Quicksort: split around a pivot

Quicksort divides the list in a different way. It picks one value, the pivot, and rearranges the list so that everything smaller than the pivot comes before it and everything else comes after it. This step is called partitioning. Now the pivot is in its final place, and the two sides can be sorted separately with the same method. Nothing needs merging afterwards, because every value on the left is already smaller than every value on the right.

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]. Total: 8 comparisons and 2 swaps.

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. Quicksort then falls back to about n²/2 comparisons: 10 for [1, 2, 3, 4, 5], the same as selection sort. Real libraries avoid this by choosing the pivot more carefully, for example at random or as the middle of three sample values.

BackgroundBoth 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. His first idea took time proportional to the square of the sentence length; his second became quicksort. He published it in 1961.
MethodComparisonsExtra memory
Insertion sortusual about n²/4, worst about n²/2none; stable
Merge sortabout n log₂ n, alwaysa second list of n values; stable
Quicksortusual about n log₂ n, worst about n²/2 (bad pivots)little; usual versions not stable
Can any comparison sort beat n log₂ n? No. For different values, there are n! possible starting orders. Here n! means n × (n − 1) × ... × 1. A sort that learns only by comparing pairs must tell all of these orders apart. Each comparison has two outcomes, so the worst case needs at least log₂(n!) comparisons, which grows like n log₂ n. For 10 values that bound is 22 comparisons.
Key points
  • 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.

Practice questions from Sorting 2: merge sort and quicksort on edubun

Embed this quiz

Free to embed. Please keep the credit line.

Sources for this course (11)
  • MIT OpenCourseWare 6.006 Introduction to Algorithms, Spring 2020 (Demaine, Ku, Solomon)
  • lecture notes 1 Introduction, 3 Sorting, 9 Breadth-First Search, 10 Depth-First Search (ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/pages/lecture-notes) and Fall 2011 lecture 13 BFS notes (ocw.mit.edu/courses/6-006-introduction-to-algorithms-fall-2011)
  • Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms (MIT Press)
  • with the CLRS-based Khan Academy algorithms unit by Thomas Cormen and Devin Balkcom of Dartmouth (khanacademy.org/computing/computer-science/algorithms: binary search, selection sort analysis, merge sort, quicksort overview and analysis)
  • MacTutor History of Mathematics, Al-Khwarizmi (mathshistory.st-andrews.ac.uk/Biographies/Al-Khwarizmi: word algorithm from the Latin title Algoritmi de numero Indorum)
  • D. E. Joyce, Euclid's Elements Book VII Propositions 1 and 2 (mathcs.clarku.edu/~djoyce/elements/bookVII)
  • Wolfram MathWorld, Merge Sort (mathworld.wolfram.com/MergeSort.html: proposed by John von Neumann in 1945, after Knuth 1998 p. 159)
  • Stanford CS "Tony Hoare: Quicksort" (cs.stanford.edu/people/eroberts/courses/soco/projects/2008-09/tony-hoare/quicksort.html: devised while a student at Moscow State University for Russian-English machine translation with a tape dictionary, programmed in Algol 60 and published 1961; the year 1959 from the Wikipedia Quicksort article and its cited sources)
  • Bodleian Libraries, Ada Lovelace (blogs.bodleian.ox.ac.uk/adalovelace: 1843 paper, Note G Bernoulli numbers)
  • Fourmilab text of Menabrea's Sketch with Lovelace's notes (fourmilab.ch/babbage/sketch.html)
  • Seven Bridges of Konigsberg (Euler 1736) and Tower of Hanoi (Edouard Lucas, 1883) checked against the Wikipedia articles and their cited sources.

Checked: 2026-10-17