All topics
36

Sorting by splitting and merging

Tier 1Locked

Where it runs

1. The problem

The sorts you wrote so far walk the list again and again. On a list of n items they make roughly n times n comparisons. For 100 items that is 10,000 comparisons, which is fine. For a million it is a trillion. You want a sort whose work grows much more slowly.

Start from a simple fact. Two lists that are already sorted are easy to combine into one sorted list. You look at the first numbers of both lists and take the smaller one, again and again. So if you already had two sorted halves, the job would be almost done.

Merge sort turns that fact into a full method. Split the list in half, sort each half, then merge the two sorted halves into one.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included
Merge sort: cut in half, then merge
mergeSort([5, 2, 4, 6, 1, 3])
arr
5
2
4
6
1
3
left
empty
right
empty
out
empty

Sort [5, 2, 4, 6, 1, 3]. Merge sort cuts at the midpoint without looking at values, sorts each half, then merges them.

Speed race
Three sorts on the same 40 numbers

One operation is one comparison or one move. Every frame, each lane does the same number of operations, so the slow one falls behind.

Bubble sort O(n²)
0 operations
Merge sort O(n log n)
0 operations
Quicksort O(n log n)
0 operations

 

And with more numbers

Operations for n numbers, and roughly how long they take at 100 million simple operations a second. An estimate from the same count, not a measurement.

n = 1,000
Bubble sort749.3K · 7.5 ms
Merge sort19.9K · under 1 ms
Quicksort18.4K · under 1 ms
n = 100,000
Bubble sort7.5B · 1.2 min
Merge sort3.3M · 33 ms
Quicksort3.1M · 31 ms
n = 10,000,000
Bubble sort75T · 8.7 days
Merge sort465.1M · 4.7 s
Quicksort430.2M · 4.3 s

Recognise it

Fast sort (merge / quick)

Say these words and it is this pattern

  • sort an array of real size (thousands+)
  • need O(n log n) guaranteed or expected
  • sort as a subroutine before another algorithm (two pointers, greedy, sweep)
  • stability required (merge sort) or in-place expected (quicksort)
  • just "sort this" with no small-n or special-key hint

Looks similar, isn't

n up to 1e6 gives O(n log n). Merge sort needs O(n) extra memory, quick sort needs O(log n).

On LeetCode

Problems that need a sort that is O(n log n) on every input, a merge of two sorted lists, or a count of pairs taken while merging. Split in half, sort each half, and merge from the front.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy