Merge Sort, step by step.

Merge sort is a divide-and-conquer sorting algorithm that splits an array into halves until single values remain and then merges the sorted parts back together. It takes O(n log n) time in every case, needs O(n) extra space and is stable. This page explains how it works, with step-by-step animations of the left half, the right half and the final merge from the VisiGrab app.

How merge sort works

What is merge sort?

Merge sort is a divide-and-conquer sorting algorithm. It splits an array into halves until single values remain, then merges sorted parts back into one sorted array. John von Neumann described it in 1945. It takes O(n log n) time in every case and O(n) extra space, and it is stable.

How merge sort works: divide and conquer

Each call sorts one part of the array in three steps. The diagrams show them on 8, 0, 5, 2, the left half of the app's default array.

1. Divide: split the part at its middle.

8, 0, 5, 2 splits into two halves: 8, 0 tinted yellow and 5, 2 tinted green.

2. Conquer: sort both halves the same way. A single value is already sorted, so the recursion stops there.

Each half is sorted on its own: 8, 0 becomes 0, 8, and 5, 2 becomes 2, 5.

3. Combine: merge the two sorted halves.

The sorted halves 0, 8 and 2, 5 merge into 0, 2, 5, 8.

Merging uses two markers, one per half. In the app they are the yellow and green "min" labels over each half's first value not yet merged; in the pseudocode below they are the indices i and j. Each half is sorted, so the value under its marker is its smallest remaining one, and only these two values can come next. The smaller one is copied into an auxiliary array, and its marker moves on. On a tie the left value goes first. When one half runs out, the rest of the other follows without comparisons. Then the merged values are copied back. This is the two-pointer technique. Merging parts of p and q values makes at most p + q − 1 comparisons and at least as many as the smaller part has values.

Merge sort pseudocode

Positions count from 0, as in the app. An odd number of values splits unevenly. Rounding the middle down gives the left part the extra value, so seven values split 4 + 3.

In pseudocode:

mergeSort(a, low, high)
    if low >= high
        return
    mid = floor((low + high) / 2)
    mergeSort(a, low, mid)
    mergeSort(a, mid + 1, high)
    merge(a, low, mid, high)

merge(a, low, mid, high)
    i = low
    j = mid + 1
    k = 0
    while i <= mid and j <= high
        if a[i] <= a[j]
            aux[k] = a[i]
            i = i + 1
        else
            aux[k] = a[j]
            j = j + 1
        k = k + 1
    for t from i to mid
        aux[k] = a[t]
        k = k + 1
    for t from j to high
        aux[k] = a[t]
        k = k + 1
    for t from 0 to high - low
        a[low + t] = aux[t]

mergeSort stops when its part holds one value or none, when low >= high. In merge, i and j are the two markers and k is the next free cell of aux, one array of n cells made once. The test a[i] <= a[j] takes the left value on a tie. The next two loops copy the rest of whichever part is left, and the last copies aux back into a[low..high]. The first call is mergeSort(a, 0, n - 1).

Merge sort example: the left half

The player sorts the left half, 8, 0, 5, 2, of the app's default array 8, 0, 5, 2, 3, 10, 1. It splits down to single values, then merges [8, 0] into [0, 8], [5, 2] into [2, 5], and those two into [0, 2, 5, 8]. In each merge the smaller front value moves down into the auxiliary array, and once one part is used up, the rest follows without a comparison.

The left half

All steps as text
  1. Sort the array using the Merge Sort algorithm.
  2. Divide the array into two halves (subarrays). The left half contains indices [0, 3], and the right half contains indices [4, 6].
  3. Focus on the left half [8, 0, 5, 2]. Process the right half [3, 10, 1] later.
  4. Split into [8, 0] and [5, 2].
  5. Examine the left subarray [8, 0]. Process the right subarray [5, 2] afterward.
  6. Both subarrays contain single items, so they are already sorted. Merge them now.
  7. Use the auxiliary array.
  8. Mark the minimum value from the left subarray — currently 8.
  9. Mark the minimum value from the right subarray — currently 0. Compare and merge these into the auxiliary array in sorted order.
  10. Since 0 is smaller than 8, copy 0 first to the auxiliary array.
  11. Copy 8 next.
  12. Transfer values from the auxiliary array back to the original array.
  13. Confirm that the merged part [0, 8] is sorted.
  14. Focus on the right subarray [5, 2] and sort it in the same way.
  15. Both subarrays contain single items, so they are already sorted. Merge them now.
  16. Use the auxiliary array again for the merging process.
  17. Mark the minimum value from the left subarray — currently 5.
  18. Mark the minimum value from the right subarray — currently 2. Compare and merge these into the auxiliary array in sorted order.
  19. Since 2 is smaller than 5, copy 2 first to the auxiliary array.
  20. Copy 5 next.
  21. Transfer values from the auxiliary array back to the original array.
  22. Confirm that the merged part [2, 5] is sorted.
  23. Revisit the subarray [0, 8, 2, 5].
  24. Prepare to merge the sorted subarrays [0, 8] and [2, 5].
  25. Use the auxiliary array again for the merging process.
  26. Mark the minimum value from the left subarray — currently 0.
  27. Mark the minimum value from the right subarray — currently 2. Compare and merge these into the auxiliary array in sorted order.
  28. Since 0 is smaller than 2, copy 0 first to the auxiliary array.
  29. Since 2 is smaller than 8, copy it to the auxiliary array.
  30. Since 5 is smaller than 8, copy it to the auxiliary array.
  31. Copy 8 next.
  32. Transfer values from the auxiliary array back to the original array.
  33. Confirm that the merged part [0, 2, 5, 8] is sorted.
  34. Three merges made five comparisons, eight copies into the auxiliary array and eight back: [8, 0, 5, 2] became [0, 2, 5, 8].
Merge Sort — The left half. Last step: Three merges made five comparisons, eight copies into the auxiliary array and eight back: [8, 0, 5, 2] became [0, 2, 5, 8].

The animation moves each value and leaves its cell empty; the code copies it.

Merge sort example: the right half

The player sorts the right half, 3, 10, 1, which splits unevenly into [3, 10] and [1]; two merges give [1, 3, 10]. Each merge fills the auxiliary array from its first cell, so these values move down and left.

The right half

All steps as text
  1. The left half is sorted: [0, 2, 5, 8]. The right half [3, 10, 1] is next.
  2. Focus on the right subarray [3, 10, 1] and sort it in the same way.
  3. Split into [3, 10] and [1].
  4. Examine the left subarray [3, 10]. Process the right subarray [1] afterward.
  5. Both subarrays contain single items, so they are already sorted. Merge them now.
  6. Use the auxiliary array for the merging process.
  7. Mark the minimum value from the left subarray — currently 3.
  8. Mark the minimum value from the right subarray — currently 10. Compare and merge these into the auxiliary array in sorted order.
  9. Since 3 is smaller than 10, copy 3 first to the auxiliary array.
  10. Copy 10 next.
  11. Transfer values from the auxiliary array back to the original array.
  12. Confirm that the merged part [3, 10] is sorted.
  13. Revisit the subarray [3, 10, 1].
  14. Prepare to merge the sorted subarrays [3, 10] and [1].
  15. Use the auxiliary array again for the merging process.
  16. Mark the minimum value from the left subarray — currently 3.
  17. Mark the minimum value from the right subarray — currently 1. Compare and merge these into the auxiliary array in sorted order.
  18. Since 1 is smaller than 3, copy 1 first to the auxiliary array.
  19. Copy 3 next.
  20. Copy 10 next.
  21. Transfer values from the auxiliary array back to the original array.
  22. Confirm that the merged part [1, 3, 10] is sorted.
  23. Two merges made two comparisons, five copies into the auxiliary array and five back. The right half is now [1, 3, 10].
Merge Sort — The right half. Last step: Two merges made two comparisons, five copies into the auxiliary array and five back. The right half is now [1, 3, 10].

Merge sort example: the final merge

The final merge of 0, 2, 5, 8 and 1, 3, 10 makes six comparisons, the most a merge of four and three values can make. 10 follows without one, and the seven values go back: 0, 1, 2, 3, 5, 8, 10.

The final merge

All steps as text
  1. Both halves are sorted: [0, 2, 5, 8] and [1, 3, 10]. One merge is left.
  2. Check the whole array: [0, 2, 5, 8, 1, 3, 10].
  3. Prepare to merge the sorted subarrays [0, 2, 5, 8] and [1, 3, 10].
  4. Use the auxiliary array for the merging process.
  5. Mark the minimum value from the left subarray — currently 0.
  6. Mark the minimum value from the right subarray — currently 1. Compare and merge these into the auxiliary array in sorted order.
  7. Since 0 is smaller than 1, copy 0 first to the auxiliary array.
  8. Since 1 is smaller than 2, copy it to the auxiliary array.
  9. Since 2 is smaller than 3, copy it to the auxiliary array.
  10. Since 3 is smaller than 5, copy it to the auxiliary array.
  11. Since 5 is smaller than 10, copy it to the auxiliary array.
  12. Since 8 is smaller than 10, copy it to the auxiliary array.
  13. Finally, copy 10.
  14. Transfer values from the auxiliary array back to the original array.
  15. The array is now completely sorted.
  16. The final merge made six comparisons, seven copies into the auxiliary array and seven back. The whole sort made six merges: 13 comparisons, 20 copies into the auxiliary array and 20 back.
Merge Sort — The final merge. Last step: The array is sorted: 0, 1, 2, 3, 5, 8, 10.

Is merge sort stable?

Yes. On a tie the merge takes the value from the left part, which came first, so equal values keep their original order; the example below shows a tie.

Why does merge sort need extra memory?

A merge writes its result while it still reads both parts, so writing into the array itself would overwrite values not yet merged. It collects the merged values in an auxiliary array of n cells instead and copies them back: O(n) extra space. The players show every copy into the auxiliary array and back.

Merge sort time complexity and the recursion tree

The figure draws the sort as a recursion tree. Seven values need three levels of splits, about log2 n. Each level of merges copies its values into the auxiliary array and back once: O(n) per level, so O(n log n) in every case. The recurrence T(n) = 2T(n/2) + O(n) gives the same by the master theorem.

A tree of array rows for 8, 0, 5, 2, 3, 10, 1. Going down under Divide, the array splits into 8, 0, 5, 2 and 3, 10, 1, then into 8, 0; 5, 2; 3, 10; and 1, then into seven single values. Going back up under Merge, the values join into 0, 8; 2, 5; 3, 10; and 1, then into 0, 2, 5, 8 and 1, 3, 10, and finally into 0, 1, 2, 3, 5, 8, 10.
Three levels of splits take seven values down to single values, and three levels of merges bring them back up, making 3, 4 and 6 comparisons. The app makes the same merges, but sorts the left half before it splits the right.

On the default array the three merge levels make 3, 4 and 6 comparisons and copy 6, 7 and 7 values each way, since 1 is alone at the lowest level. In all, six merges make 13 comparisons and 40 copies, and no swaps.

CaseComparisonsSeven valuesTimeExtra space
BestAbout (n/2) log2 n9O(n log n)O(n)
AverageA little below the worst case12.7O(n log n)O(n)
Worstn⌈log2 n⌉ − 2⌈log2 n⌉ + 114O(n log n)O(n)

Every order of seven values makes the same 40 copies; only the comparisons vary. A sorted array is not the best case: it makes one comparison per left value in each merge, 11 in all. The reversed array makes one per right value, and the right part is never the larger: 9.

Merge sort space complexity: is it in-place?

The auxiliary array of n values and the O(log n) recursion stack make O(n) extra space, not O(n log n): versions that copy the halves allocate more in all, but hold only O(n) at a time. So merge sort is not in-place. In-place merging exists, but it is complex or slower.

On a linked list, merging relinks nodes, so only the O(log n) stack is extra. Finding the middle takes a walk along the list, O(n) per level, so the sort stays O(n log n).

Note

Java's LinkedList has no sort of its own: List.sort copies it into an array, sorts that and writes the values back. C++'s std::list::sort merges by relinking nodes.

Why merge sort is stable

A stable sort keeps equal values in their original order. Merge sort is stable because a tie takes the left value, which came first. Merging [2a, 3] and [1, 2b], 1 goes first. 2a and 2b are equal, so 2a, the left one, goes next. Then come 2b and 3: 1, 2a, 2b, 3.

A row of four cells holding two sorted parts: on the left a 2 marked a and 3, on the right 1 and a 2 marked b. Below it, the auxiliary array holds 1, the 2 marked a, the 2 marked b and 3: the two equal 2s keep their original order.
On the tie the merge takes the 2 from the left part first, so the equal values keep their original order: merge sort is stable.

A strict "smaller than" test would take 2b first: still sorted, but not stable. The app's animation takes the left value, and only an array of your own with equal values shows its tie step.

Is merge sort adaptive?

Not in its basic form: it splits and merges the same way whatever the order, and in the app any seven values take 75 steps. Skipping a merge when the left part's last value is not larger than the right part's first makes sorted input O(n). Natural merge sort, and Timsort in Python and Java, merge runs that are already in order, so partly sorted data sorts faster.

Merge sort vs quick sort, heap sort and insertion sort

On the array 8, 0, 5, 2, 3, 10, 1, merge sort makes 13 comparisons and 40 copies, insertion sort 16 comparisons and 11 shifts, and selection sort 21 comparisons and five swaps. On so few values the simple sorts do less work, so library sorts hand small parts to insertion sort.

PropertyMerge sortQuick sortHeap sortInsertion sort
Average timeO(n log n)O(n log n)O(n log n)O(n2)
Worst timeO(n log n)O(n2)O(n log n)O(n2)
Extra spaceO(n)O(log n) stack on averageO(1)O(1)
StableYesNoNoYes

Of the three O(n log n) sorts, quick sort is usually the fastest on data held in memory and heap sort the slowest. Merge sort pays O(n) memory for its guarantees. Merge sort vs quick sort: full comparison →

Bottom-up (iterative) merge sort

The app's version is top-down and recursive. Bottom-up merge sort is iterative: it merges single values into pairs, pairs into fours and so on, with no recursion stack. For seven values it makes the app's six merges, level by level.

Merge sort in Python, Java and C++

The app shows the code in all three, linked to the full source on GitHub. It splits at (start + end) / 2, rounded down.

Note

In Java and C++, (start + end) / 2 can overflow int on arrays of over about a billion values; start + (end - start) / 2 avoids it. Python's integers do not overflow.

Python's list.sort() and sorted() and Java's sorts for objects use Timsort, a stable merge sort hybrid with temporary memory of at most n/2 items. C++'s std::stable_sort merges through a buffer, or in O(n log2 n) without one.

The full source code is on GitHub, in Python, Java and C++.

When merge sort is used

Merge sort suits:

  • External sorting of data too large for memory. Memory-sized runs are sorted, then merged many at a time through a min-heap of their front values. The app's info dialog ends on this use.
  • Sorting records by one key after another, where stability matters.
  • Parallel sorting, since the two halves are independent.
  • Counting inversions, pairs of values in the wrong order. Each time a right value is copied, add the number of left values still waiting. The default array has 11.

For descending order, take the larger front value first, and still the left value on a tie.

Three animations here.
The whole topic in the app.

In VisiGrab merge sort runs on the default, a random or your own array of seven values, with a step for every split, min label and copy: 75 steps for any seven values.

Your own array

Random picks seven distinct values from 0 to 19. Custom opens a seven-cell dialog for values from 0 to 99, equal ones included, with buttons for an ascending fill, which takes 11 comparisons, or a descending one, which takes 9. Equal values bring out the tie step.

Forward and back

Step forward and back through all 75 steps, every split, min label, copy and copy back with its message. Restart replays the array, and the last random or custom array comes back next time, shared with bubble, selection, insertion and quick sort.

Theory and complexity

One page: splitting down to single elements and merging back, out-of-place with O(n) auxiliary space, stable, not adaptive, O(n log n) in every case, and why merge sort suits external sorting.

Python, Java and C++

The mergeSort, mergeSortRec and mergeBothParts methods in Java and merge_sort, merge_sort_rec and merge_both_parts in Python and C++, with links to the full source on GitHub. After the last step, a hint points to the code.

Quiz

Eight questions with an explanation for every answer, from when the splitting stops to why a sorted array is no faster.

Five more sorts

Bubble sort, selection sort, insertion sort, heap sort and quick sort each have a topic of their own.

Sort an array
merge by merge.

Download VisiGrab and step through every split, copy and merge, on the default array, a random one or an array of your own.

Merge sort is one of 30+ topics. See them all