Find a course

Module 3: Searching and SortingLesson 9 of 1314 min

Merge Sort, Quicksort and the Limits of Sorting

Use divide and conquer to sort in O(n log n), compare merge sort and quicksort, see why comparison sorts can't beat n log n, and avoid built-in sort traps.

Step 1 of 10Learn

Divide, conquer, merge

Merge sort is the classic divide-and-conquer algorithm:

  1. Divide: split the array into two halves.
  2. Conquer: sort each half recursively. An array of one element is already sorted, which is the base case.
  3. Combine: merge the two sorted halves into one sorted array.

Merging is the clever part. Keep a pointer at the start of each sorted half. Compare the two front elements, move the smaller one to the output, and advance that pointer. When one half runs out, copy the rest of the other. Each step places one element, so merging n elements takes O(n) time.

Why is the whole sort O(n log n)? Picture the recursion tree. The array is halved repeatedly until pieces have one element, which takes about log₂ n levels. At every level, the merges together touch all n elements once. So the total work is n per level times log₂ n levels: O(n log n). For a million elements, that's about 20 million operations instead of the trillion a quadratic sort might need.

Merge sort's running time is O(n log n) in the best, average and worst case; no input can slow it down. It's stable if the merge takes from the left half when elements are equal. Its main cost is memory: the standard array version needs O(n) extra space for merging. It's well suited to linked lists, where merging needs no extra array, and to sorting data too large for memory, in chunks on disk.

Merge sort on 38, 27, 43, 3: split down to single items, then merge sorted halves back up3827433split3827433split3827433single items2738343merge3273843merge

Step 2 of 10Practice · Code challenge

Write merge(a, b) that takes two arrays already sorted in ascending order and returns a new sorted array containing all their elements, in O(a.length + b.length) time. Don't use sort.

Runs in a sandbox in your browser.
  • merge([1, 4, 9], [2, 3, 10])
  • merge([], [5, 6])
  • merge([7], [])
  • merge([1, 1, 2], [1, 3])
  • merge([5, 6, 7], [1, 2])

Step 3 of 10Learn

Quicksort

Quicksort also divides and conquers, but does the hard work before recursing instead of after.

  1. Choose a pivot element.
  2. Partition: rearrange the array so everything smaller than the pivot comes before it and everything larger comes after. The pivot is now in its final position.
  3. Recursively quicksort the left part and the right part. No merging needed.

Partitioning takes O(n) time and can be done in place with swaps. If the pivot splits the array roughly in half each time, there are about log₂ n levels of recursion, giving O(n log n), the same as merge sort.

But if the pivot is consistently the smallest or largest element, one side is empty and the other has n − 1 elements. The recursion is then n levels deep, and the total work is about n²/2: O(n²). A naive version that always picks the first element as pivot hits exactly this worst case on input that's already sorted, a very common situation in practice.

The fix is a good pivot choice: pick a random element, or the median of three (first, middle and last). With random pivots, the worst case becomes astronomically unlikely, and the expected time is O(n log n).

Quicksort is usually not stable, but it's in place, using only O(log n) stack space on average, and very fast in practice thanks to cache-friendly partitioning. Many standard libraries use quicksort variants, such as introsort, which falls back to another algorithm if recursion gets too deep.

Quicksort partition around pivot 5: smaller values move left, larger move right, and 5 lands in its final place72945choose pivot24579after partitionThen recurse on [2, 4] and [7, 9]; no merge step is needed

Step 4 of 10Practice · Choose one

A quicksort implementation always uses the first element as the pivot. On which input does it perform worst?

Step 5 of 10Learn

Can we sort faster than n log n?

Merge sort, quicksort on average, and heapsort all run in O(n log n). Is there a cleverer comparison sort waiting to be discovered? No, and it's possible to prove it.

Any sort that works only by comparing pairs of elements can be drawn as a decision tree: each comparison is a node with two outcomes, and each leaf is one possible final ordering. To sort every possible input correctly, the tree must have a leaf for each of the n! orderings of n elements. A binary tree with n! leaves has height at least log₂(n!), and log₂(n!) grows like n log₂ n. So every comparison sort needs Ω(n log n) comparisons in the worst case. Merge sort is optimal, up to constant factors.

The bound has a loophole: it only applies to algorithms that learn about the data through comparisons. If you know more about the keys, you can do better:

  • Counting sort: for integers in a small range 0 to k, count how many times each value occurs, then write them out. O(n + k) time.
  • Radix sort: sort numbers or fixed-length strings digit by digit using a stable counting sort at each digit. O(d·(n + k)) for d digits.
  • Bucket sort: distribute uniformly spread values into buckets, sort each small bucket, and concatenate.

These are excellent when their assumptions hold, such as sorting millions of ages, ZIP codes or exam scores, but they don't work for arbitrary objects compared by a custom rule.

Decision tree for sorting three items a, b, c by comparisons: six possible orders need at least three comparisons in the worst casea<b?b<c?a b ca<c?a c bc a ba<c?b a cb<c?b c ac b a3! = 6 leaves need depth ≥ log₂ 6 ≈ 2.6, so 3 comparisons

Step 6 of 10Practice · Work it out

There are 8! = 40,320 possible orderings of 8 distinct items. What is the minimum number of comparisons any comparison sort must make in the worst case to sort 8 items? (215 = 32,768 and 216 = 65,536.)

Step 7 of 10Learn

Using built-in sorts safely

In real code you'll almost always use your language's built-in sort. It's thoroughly tested, highly optimized, and usually a hybrid: Python and modern JavaScript engines use Timsort, which combines merge sort with insertion sort and is especially fast on data that's partly sorted. Since the ECMAScript 2019 standard, JavaScript's Array.prototype.sort is required to be stable.

JavaScript has one notorious trap. Without a comparison function, sort() converts elements to strings and compares them alphabetically. So [10, 9, 1, 100].sort() returns [1, 10, 100, 9], because the string 10 comes before the string 9. Always pass a comparator for numbers:

nums.sort((a, b) => a - b);  // ascending
nums.sort((a, b) => b - a);  // descending

The comparator returns a negative number if a should come first, positive if b should come first, and 0 if they're equal. For objects, compare a field: people.sort((a, b) => a.age - b.age). For strings in human languages, a.localeCompare(b) handles accents and case sensibly.

Also remember that sort mutates the original array. If you need to keep the original, copy it first with [...arr] or use toSorted() where it's available.

Knowing the algorithms underneath helps you predict costs: sorting is O(n log n), so sorting inside a loop that runs n times is O(n² log n), often a sign that you should sort once outside the loop.

Step 8 of 10Practice · True or false

In JavaScript, [10, 9, 1].sort() returns [1, 9, 10].

Step 9 of 10Practice · Sort into groups

Sort these algorithms by whether their standard versions are stable.

Tap an item, then tap its group (or drag it there).

Step 10 of 10Practice · What would you do?

What would you do?

You're sorting 50 million customer records by signup date on a server with plenty of memory. Records with the same date must stay in their current order, which is alphabetical by name. Which choice fits best?