COMPARISON SORTS
Merge Sort, visualised
Merge sort splits the array in half repeatedly and then merges the sorted halves back together until the whole array is sorted.
Run Merge Sort in the visualizer →
Opens the Sorting Cinema visualizer with 16 elements in English.
How it works
- Split the array at the middle and recurse until each part has one element.
- Compare the fronts of the two sorted parts and write back the smaller one (the left one on ties).
- When one part runs out, copy the rest of the other part.
- Merged runs grow longer until the whole array is sorted.
Complexity and stability
- Best
- O(n log n)
- Average
- O(n log n)
- Worst
- O(n log n)
- Extra space
- O(n)
- Stability
- Can be implemented stably (this app takes the left value on ties)
For any input the split depth is log n levels and each level of merging is O(n), so best, average and worst cases are all O(n log n). Merging uses O(n) extra array space.
Source of facts: Complexity follows the learning guide's comparison table and text, and this app's implementation.
Trace on a small array
The first operations on the input [5, 2, 4, 1, 3], following the same steps as the app.
| # | Operation | Array after |
|---|---|---|
| 1 | Write 2 to [0] | [2, 2, 4, 1, 3] |
| 2 | Write 5 to [1] | [2, 5, 4, 1, 3] |
| 3 | Write 2 to [0] | [2, 5, 4, 1, 3] |
| 4 | Write 4 to [1] | [2, 4, 4, 1, 3] |
| 5 | Write 5 to [2] | [2, 4, 5, 1, 3] |
| 6 | Write 1 to [3] | [2, 4, 5, 1, 3] |
| 7 | Write 3 to [4] | [2, 4, 5, 1, 3] |
| 8 | Write 1 to [0] | [1, 4, 5, 1, 3] |
…and so on. In this trace, 12 compare / swap / write operations in total produce [1, 2, 3, 4, 5].
Suitable inputs and caveats
- Its running time depends little on the input order.
- In this app you can watch the halves being copied and written back one element at a time.
- Needing extra space is the main difference from quick sort and heap sort.
FAQ
What is the difference between merge sort and quick sort?
Both average O(n log n), but quick sort can degrade to O(n²) with unbalanced partitions, while merge sort keeps O(n log n) in the worst case by using extra array space.
Is merge sort stable?
It can be implemented stably. This app writes back the left element first on ties, so equal values keep their original order.