Quick Answer

Merge sort sorts a list in 3 steps. They are split, sort the halves and merge. Splitting stops at single items. The merge step does the real work. Time is O(n log n) in every case. Extra space is O(n). Python and C++ code below was executed.

Merge sort is a sorting algorithm with a speed guarantee. No input can push the cost past O(n log n).

Most tutorials draw the splitting and rush the merge. Here the merge gets the most space because the merge is where the work happens.

Trace, tested code, call counts and timings follow below.

What Is Merge Sort?

Plan is plain. Split the list in half and sort every half. Then merge the 2 sorted halves into one sorted list.

This plan belongs to the divide and conquer family like quick sort.

Halves are sorted by the same plan so the function calls the function again on smaller lists. That makes it a close relative of recursion. Splitting stops at one item because one item is already sorted.

Other sorts are compared on the sorting algorithms lesson.

How Does Merge Sort Work Step by Step?

Take the list 29, 10, 14, 37, 13 and 5. Splitting gives 29, 10, 14 and 37, 13, 5. Splitting continues until 6 single items remain.

Step #1: Split Until One Item Remains

What you get. Pieces that are sorted already. Every split cuts the list at the middle index.

Step #2: Sort the Halves With the Same Plan

What you get. Small problems at every level. Every call trusts the call below it to return a sorted list.

Step #3: Merge Two Sorted Lists

What you get. One sorted list from 2 sorted lists. Compare the front items and take the smaller one. Repeat until a list is empty and add the leftover items.

Table below shows all 5 merges in the order the Python code performs them. Output comes from the tested function.

MergeLeft listRight listResult
1101410, 14
22910, 1410, 14, 29
31355, 13
4375, 135, 13, 37
510, 14, 295, 13, 375, 10, 13, 14, 29, 37

Watch every split and merge on the merge sort visualiser.

How Do You Code Merge Sort in Python and C++?

Python version below has 2 functions. One splits the list and the other merges 2 sorted lists.

def merge_sort(items):
    if len(items) <= 1:
        return items
    mid = len(items) // 2
    left = merge_sort(items[:mid])
    right = merge_sort(items[mid:])
    return merge(left, right)


def merge(left, right):
    result = []
    i = 0
    j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    result.extend(left[i:])
    result.extend(right[j:])
    return result

C++ version below sorts a vector in place with a temporary copy of both halves. Standard vectors replace the fixed size arrays that some tutorials use.

#include <iostream>
#include <vector>

void mergeRange(std::vector<int>& a, int low, int mid, int high) {
    std::vector<int> left(a.begin() + low, a.begin() + mid + 1);
    std::vector<int> right(a.begin() + mid + 1, a.begin() + high + 1);
    size_t i = 0, j = 0;
    int k = low;
    while (i < left.size() && j < right.size()) {
        if (left[i] <= right[j]) a[k++] = left[i++];
        else a[k++] = right[j++];
    }
    while (i < left.size()) a[k++] = left[i++];
    while (j < right.size()) a[k++] = right[j++];
}

void mergeSort(std::vector<int>& a, int low, int high) {
    if (low >= high) return;
    int mid = low + (high - low) / 2;
    mergeSort(a, low, mid);
    mergeSort(a, mid + 1, high);
    mergeRange(a, low, mid, high);
}

int main() {
    std::vector<int> a = {29, 10, 14, 37, 13, 5};
    mergeSort(a, 0, static_cast<int>(a.size()) - 1);
    for (int x : a) std::cout << x << " ";
    std::cout << "\n";
    return 0;
}

Tested. Python 3.13.18 matched the built in sorted function on 2,000 random lists.

It also passed the empty list, a single item and a list of equal values. g++ 13.3 compiled the C++ sample with warnings on and printed 5 10 13 14 29 37. Tests ran in a cloud sandbox.

What Is the Time Complexity of Merge Sort?

Time is O(n log n) in the best, average and worst cases. Halving gives about log n levels and merging touches all n items at every level. Space is O(n) because merging builds new lists.

One million items need about 20 million steps. That value comes from n times log base 2 of n.

Test below counted comparisons for 1,024 items. None of the 3 inputs went above n times log base 2 of n which is 10,240.

Input orderComparisons
Already sorted5,120
Reverse sorted5,120
Random8,965

Timings for 100,000 items with the best of 3 trials in CPython 3.13.18 were 0.116 s for sorted input and 0.115 s for reverse input. Random input took 0.183 s. Times differ by a constant factor and not by growth order.

What Happens to Equal Items in Merge Sort?

Yes. When 2 items are equal the merge step takes the left one first. Equal items remain in their original order and that property is called stability.

Test input was 4 records with keys 2, 1, 2 and 1 and labels a, b, c and d. Output order was b, d, a and c so equal keys retained label order. Python documents the same guarantee for its own sort in the Sorting HOW TO.

Which Is Better in Merge Sort vs Quick Sort?

Table below compares both sorts on the points that matter for a choice.

PointMerge sortQuick sort
Worst case timeO(n log n)O(n squared)
Extra spaceO(n)Small (sorts in place)
StableYesNot by default
Good forGuaranteed time, stable order, data on diskMemory tight, in place sorting

Choose it when you need a time guarantee or stable order. Choose quick sort when memory is tight. Both beat bubble sort by a wide margin on large lists.

Practice more problems in the sorting practice set.

Frequently Asked Questions

How Many Steps Does the Algorithm Need?

It is O(n log n) in the best, average and worst cases. Space is O(n) because the merge step needs extra memory.

Why Is the Cost the Same for Every Input?

It always splits the list evenly in half. The even split removes the worst case.

Is Merge Sort Stable?

Yes. The merge step takes the left item first when 2 items are equal. Equal items remain in their original order.

What Is the Difference Between Merge Sort and Quick Sort?

Both use divide and conquer. Quick sort sorts in place but can reach O(n squared). Merge sort remains at O(n log n) and is stable but needs extra memory.

Why Does the Merge Step Use Extra Memory?

The merge step builds new lists and does not rearrange the original in place. That temporary space adds up to O(n).

Does This Sort Suit Large Datasets?

Yes. It can sort chunks of data separately and merge them. That makes it a fit for data too large for memory.

Can a Loop Replace the Recursion?

Yes. Bottom up code merges pieces of size 1 then 2 then 4 and so on with a loop. Recursive code above is clearer to follow.

What Should You Remember About Merge Sort?

Split to single items and merge upward. That even split gives a time guarantee and stable order.

Key takeaways.

  • Cost is O(n log n) on every input.
  • The cost is O(n) extra memory.
  • Merge sort vs quick sort is a choice between a guarantee and low memory.

Check yourself. Merging 3, 27 and 38, 43 places the value 3 first.