Merge sort and quick sort
1 Two ways to split the work
The simple sorts from the last lesson compare values in pairs, about n² times. At n = 10⁵ that is around 10¹⁰ steps. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE).
A teacher with a tall pile of answer sheets would split the work. Two helpers each take half the pile, and each one splits their half again the same way. A pile of one sheet is already sorted. This is divide and conquer, and it takes about n log n steps. The two sorts here split the pile in different ways:
- Merge sort cuts the pile in the middle without looking at the marks. The work comes at the end, when two sorted piles are merged into one.
- Quick sort does the work first. It puts low marks in one pile and high marks in the other. When both piles come back sorted, the low pile goes first, and nothing needs merging.
We sort the same 8 values with both:
2 Merge sort: cut down, merge up
Merge sort cuts the array in the middle, sorts each half by calling itself, and merges the two sorted halves. A part with one value is already sorted. That is the base case.
The drawing shows a whole run, one row per level of calls. Each tint marks one part. On the way down, every row cuts each part in two. On the way up, every row merges neighbouring parts in pairs.
On the way down, the values never move. The cuts only decide where each part begins and ends. All the sorting happens on the way up, in the merges, so the merge is the step to get right.
3 Merging two sorted halves
The last merge joins [2, 4, 7, 8] and [1, 3, 5, 6], which sit side by side in nums. Both halves are sorted, like the helpers' two piles, so the smallest value left is always at the front of one of them. We keep a pointer on each front: i on the left half and j on the right half. At each step, we compare nums[i] with nums[j], copy the smaller one into a new array merged, and move that pointer on.
When one half runs out, the rest of the other half is sorted and larger than everything in merged, so we copy it as it is. Every value moves once, so merging n values takes about n steps.
In the code, sortRange(nums, lo, hi) sorts the part from lo to hi, both ends included. The middle is lo + (hi - lo) / 2. The mistakes section shows why it is not (lo + hi) / 2.
C++
The & matters. vector<int>& nums hands every call the same array. Without the &, each call sorts its own copy, and the caller's array stays as it was.
Every call shares one array. An int[] is passed by reference, so each call changes the caller's array. merged can be a plain array, because its length, hi − lo + 1, is known.
Use // for the middle. / gives a float, and a float cannot be an index. We pass lo and hi instead of slices, because a slice is a copy, and sorting a copy leaves nums as it was.
Round the middle down. / keeps the fraction, so (7 − 0) / 2 is 3.5, and nums[3.5] is undefined. Math.floor makes it 3.
A slice shares its array. Every call changes the caller's array through nums. copy writes merged back over nums[lo:hi+1].
Indexes are usize. They cannot go below 0, so n - 1 on an empty vector would panic. The n > 1 check avoids it. The helpers take a slice, &mut [i32], and a &mut Vec<i32> turns into one by itself.
Every call shares one array. An int[] is passed by reference, so each call changes the caller's array.
Our example comes out as [1, 2, 3, 4, 5, 6, 7, 8] in every language.
4 Why merge sort is O(n log n)
The way-up drawing shows the cost. Every row holds all 8 values, and building a row moves each value once. So each row of merges costs about n steps.
Each row doubles the size of the parts: 1, 2, 4, 8. Doubling from 1 up to n takes log₂ n rows, so 8 values need 3 rows of merges. This is the recursion tree from the earlier lesson, counted one level at a time.
At n = 10⁵, log n is about 17, so the sort takes around 2 × 10⁶ steps, well inside the time limit. The cuts always fall in the middle, whatever the values are. So the best, average and worst cases are all O(n log n).
- Space: O(n). The last merge builds
mergedwith all n values. The call stack adds only about log n frames, one per level. - Stable. On a tie,
nums[i] <= nums[j]takes the left value first. The left value came earlier in the array, so equal values keep their order.
Below, 5a and 5b are equal values, and 5a came first. Merging [3, 5a] with [5b, 9] shows what the tie rule decides:
5 Quick sort: partition around a pivot
Quick sort picks one value, the pivot, as the line between low and high. It moves the values so that the left part holds values at most the pivot, and the right part values at least the pivot. This step is the partition. Then a recursive call sorts each part, and nothing needs merging.
For now, the pivot is the first value. Hoare's partition moves two pointers towards each other:
- i walks right from the left end, past values smaller than the pivot.
- j walks left from the right end, past values larger than the pivot.
- When both stop with i left of j, the two values are on the wrong sides. We swap them, and both pointers step in.
- When i is no longer left of j, the partition returns j.
The tints show the rule the loop keeps. Every value left of i is at most 4, and every value right of j is at least 4. When the pointers cross, no value is left unchecked.
| Round | i stops on | j stops on | Then | nums after |
|---|---|---|---|---|
| 1 | 4, at 0 | 3, at 7 | swap | [3, 2, 8, 7, 6, 1, 5, 4] |
| 2 | 8, at 2 | 1, at 5 | swap | [3, 2, 1, 7, 6, 8, 5, 4] |
| 3 | 7, at 3 | 1, at 2 | crossed, return 2 | no change |
The pivot 4 ended at index 7. Hoare's partition does not put the pivot in its final place. It only makes sure that no value in 0..2 is larger than any value in 3..7. So quick sort next sorts lo..j and j + 1..hi, here 0..2 and 3..7.
6 Choosing the pivot
The first value is a bad pivot for a sorted array. On [1, 2, …, 8], the pivot 1 is the smallest value, so j walks all the way down to it. The parts are [1] and the other 7 values. The next call peels off 2, then 3, and so on.
The rows partition 8 values, then 7, then 6, about n²/2 steps in all. At n = 10⁵ that is around 5 × 10⁹ steps, so it gets TLE. The recursion also goes 10⁵ calls deep and can overflow the stack first. Any fixed rule, such as the first, last or middle value, has some input that hits it on every call.
The fix is small. We pick the pivot at a random index and swap it to the front. The partition stays the same.
A random pivot rarely splits badly. Half the values sit in the middle half of the sorted order, so the pivot lands there half the time. Then neither part holds more than three quarters of the values. The tree stays about log n levels deep, a few times deeper than merge sort's, and each level partitions at most n values. So the average time is O(n log n).
C++
rand() gives a large random int, and % (hi - lo + 1) turns it into an offset from lo.
One Random for the whole class. Making a new one on every call works, but wastes time. nextInt(k) gives 0 to k − 1.
random.randint(lo, hi) includes both ends, unlike range. It needs import random at the top of the file.
Math.random() gives a fraction from 0 up to 1. Multiplied by the size of the part and rounded down, it gives an offset from lo.
rand.Intn(k) from math/rand gives 0 to k − 1. Go seeds it randomly on its own.
The standard library has no random numbers. random_index takes them from RandomState, the random seed behind HashMap. Each RandomState::new() hashes with fresh keys, so finish() gives new bits each time.
Random.Shared.Next(lo, hi + 1) leaves out its upper bound, so we pass hi + 1.
Quick sort works in place: it only swaps values inside nums. Its only extra memory is the call stack, about log n frames on average.
7 Mistakes and edge cases
- A middle that overflows.
(lo + hi) / 2passes theintlimit, about 2 × 10⁹, when both are above 10⁹. Indexes here stay small, but the same line in a binary search over values does not.lo + (hi - lo) / 2never overflows. - Losing the leftovers. A merge that stops when one half runs out drops the rest of the other half. Our last merge would lose 7 and 8.
<instead of<=in the merge. The output is still sorted, but ties come from the right half first, so the sort is no longer stable.- Wrong bounds. In merge sort, parts lo..mid − 1 and mid..hi never end on two values. For lo = 0 and hi = 1, mid is 0, and the right part is 0..1 again. The calls go on until the stack overflows, a Runtime Error. In quick sort, sorting lo..j − 1 and j + 1..hi skips
nums[j], as if the pivot sat there. With the first value as pivot, our example comes out as [2, 3, 1, 4, 6, 5, 7, 8], a Wrong Answer. - Many equal values. On [4, 4, 4, 4], our partition stops on every 4 and swaps, so the parts come out even. A partition that sends every value equal to the pivot to one side, as Lomuto's does, splits them n − 1 and 0 and is O(n²) again. Writing
<=in our walks is worse: i runs off the end. A three-way partition is another fix. It keeps the values equal to the pivot in a middle part that needs no more sorting.
8 Which sort, and when
| Merge sort | Quick sort, random pivot | |
|---|---|---|
| Best time | O(n log n) | O(n log n) |
| Average time | O(n log n) | O(n log n) |
| Worst time | O(n log n) | O(n²), very unlikely |
| Extra space | O(n) | O(log n) stack, on average |
| Stable | Yes | No |
| In place | No | Yes |
Quick sort is not stable, because a swap can jump a value over equal values. With the first value as pivot, [2a, 2b, 1] comes out as [1, 2b, 2a].
In most problems, the library sort is the right call. It is O(n log n), well tested, and built from these same ideas.
C++
sort is not stable. It is a quick sort that switches to heap sort when the recursion gets deep, so it stays O(n log n). stable_sort is a merge sort and keeps ties in order.
Arrays.sort on an int[] is a quick sort. That is fine, because equal ints look the same. On objects, and in Collections.sort, it is a merge sort and stable.
sort and sorted are stable. They use Timsort, a merge sort that also spots runs that are already in order.
sort is stable, as the language requires. For numbers, always pass (a, b) => a - b.
slices.Sort is not stable. It is a quick sort variant. slices.SortStableFunc keeps ties in order.
sort is stable, a merge-based sort. sort_unstable is a quick sort variant, for when ties do not matter.
Array.Sort is not stable. It is a quick sort that switches to heap sort when needed. LINQ's OrderBy is stable.
We write one of these sorts ourselves in three cases:
- The problem forbids the library. Sort an Array does, and so do the merge sort and quick sort problems in this section.
- The merge step does the work. Some problems count pairs where an earlier value is larger than a later one. Every such pair meets during some merge, one value in each half. A later lesson, on counting pairs while merge sorting, builds on this.
- Only part of the order matters. One partition puts every value on the correct side of the pivot. To find the k-th smallest value, we recurse only into the side that holds it.
The next lesson goes the other way: counting sort and bucket sort order small values without comparing them at all.
Before writing a sort, check whether the library sort will do. When you do write one, test it first on a sorted array and on an array of equal values.
Practice it
- Merge sortMedium
- Quick sortMedium
- Sort an ArrayMedium
- Largest NumberMedium
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.