See merge sort split 6 3 8 2 7 1 into halves and merge them back in order. Animated step by step with the code beside it, O(n log n) time and your own input.
About this algorithm
Merge sort splits the array in half, sorts each half, and merges the two sorted halves into one. It takes O(n log n) time on every input and keeps equal values in their original order. The splitting continues until each piece holds a single value, which is sorted by definition, and then the merges rebuild the array in order.
Pick merge sort when you need a guaranteed n log n running time and a stable sort, for example ordering records by date while keeping ties in the order they came. It is also the natural sort for linked lists, where merging needs no extra array, and for data too big for memory, sorted in chunks and merged from disk. Its cost is O(n) extra memory for the merge. Quick sort is usually faster in memory and sorts in place but can degrade to n² on bad pivots. Heap sort also guarantees n log n with O(1) extra space but is not stable. For small or nearly sorted inputs, insertion sort wins.
For the slice from left to right, compute mid = floor((left + right) / 2). A slice with one value is already sorted, so return.
Recursively sort left..mid, then mid + 1..right. When both calls return, each half is in order.
Copy the two halves aside. Compare the front value of each and write the smaller one into the next slot of the array. On a tie take the left one, which is what keeps the sort stable.
When one half runs out, the rest of the other half is already in order and bigger than everything placed so far, so copy it straight in.
This page opens on 40 random bars, so type 6,3,8,2,7,1 into the Custom box to follow along. The array splits into 6 3 8 and 2 7 1. The left half splits into 6 3 and 8; merging 6 with 3 gives 3 6, and merging that with 8 gives 3 6 8. The right half splits into 2 7 and 1; merging gives 2 7, then 1 2 7. The final merge compares fronts: 1 beats 3, 2 beats 3, then 3, 6 and 7 go in as each is the smaller front, and 8 is copied over as the leftover. The result is 1 2 3 6 7 8 after 10 comparisons, five of them in that last merge.
This page splits recursively from the top. The bottom-up version skips the recursion: merge neighbouring runs of size 1, then size 2, then 4, until one run covers the array. Both do the same merges and the same amount of work.
Time: halving gives about log n levels of slices, and the merges on each level touch every value once, so the work is n per level times log n levels. Space: each merge copies its two halves into temporary arrays, up to n values for the final merge, plus a recursion stack log n deep.