
Merge sort is a sorting algorithm based on divide and conquer. It breaks a list into smaller lists, sorts those lists, and merges them until one sorted list remains. This approach also provides the foundation for external sorting, where the data is too large to fit in memory.
This article is part of a series adapted and expanded from my Medium article, published August 5, 2024, and my merge sort repository.
The animation below follows the list [8, 3, 5, 1] from its original order to the sorted result. Read each step with the animation: first the algorithm splits the list, then it joins small sorted runs back together.

Follow the animation step by step
- Start with the unsorted list:
[8, 3, 5, 1]. The values are not in ascending order yet. - Split into halves: divide the list into
[8, 3]and[5, 1]. No values are sorted or discarded; they are only separated into smaller runs. - Keep splitting: divide those runs again until each contains one value:
[8],[3],[5], and[1]. A one-value run is already sorted, so the divide phase is complete. - Merge each pair in order: compare
8with3; take3first, then8, producing[3, 8]. Compare5with1; take1first, then5, producing[1, 5]. - Merge the two sorted runs: compare the first remaining values in
[3, 8]and[1, 5]. Take1, then3, then5, then the remaining8. The final list is[1, 3, 5, 8].
At every merge, choose the smaller front value from the two runs. When one run is empty, append everything left in the other run. That is why the result stays sorted and every input value appears exactly once.

The three ideas behind merge sort
- Divide: recursively split each run into smaller halves.
- Conquer: stop when a run has zero or one value; it is already sorted.
- Combine: merge two sorted runs by repeatedly taking the smaller front value.
The animation shows one small example, but the same process works for any list. For n values, merge sort takes about n log₂(n) comparisons and needs temporary space to hold values during merging.


