Merge Sort Explained: Easy 7-Step-by-Step Guide with Python Code

If you have worked through bubble sort, selection sort and insertion sort, you have probably noticed something a little annoying. They all work, but they all get painfully slow once the list gets big. Sort a few thousand items and you barely notice. Sort a few million and your program just sits there.

That is exactly where merge sort comes in.

Merge sort is one of the most popular sorting algorithms in computer science, and for good reason. It is fast, it is predictable, and once you understand the idea behind it, it feels almost obvious. In this guide, I will walk you through how the merge sort algorithm works, show you a full merge sort example by hand, give you clean merge sort Python code, and explain its time complexity in plain English.

No heavy math. No jargon dumps. Just a clear explanation you can actually follow.

What Is Merge Sort?

Merge sort is a sorting algorithm that uses a strategy called divide and conquer. Instead of trying to sort one giant messy list in one go, it breaks the problem into smaller, easier pieces, solves those, and then stitches the results back together.

The whole thing boils down to three moves:

  1. Divide the list into two halves.
  2. Conquer by sorting each half (using merge sort again, which is where recursion comes in).
  3. Merge the two sorted halves into one sorted list.

That is it. The clever part is that merging two lists that are already sorted is very quick, and a list with just one item is always sorted by default.

Merge sort was invented by John von Neumann back in 1945, and it is still taught in nearly every computer science course today. That tells you something about how well the idea holds up.

A Real-Life Analogy to Make It Click

Imagine you have a huge stack of 200 exam papers that need to be sorted by student name. Sorting the whole pile at once would be a nightmare.

So you do this instead. You split the pile in half and hand one half to a friend. They split their pile in half again and pass it on. This keeps going until everyone is holding just one paper. One paper is obviously already sorted.

Now people start combining. Two people, each holding one paper, put them in order and make a pile of two. Two piles of two get combined into a sorted pile of four, and so on, until all the piles have merged back into one perfectly sorted stack.

Nobody ever had to deal with the full mess. Everyone just handled a small, simple job. That is merge sort.

How Merge Sort Works, Step by Step

Let’s sort this list together:

[38, 27, 43, 3, 9, 82, 10]

Try it yourselfStep 1 of 7

Watch Merge Sort in Action

Follow the list as it is split into single values, then merged back together in sorted order.

DividingMerged (sorted)Latest step

Phase 1: Keep Splitting

We split the list in half again and again until every piece has only one element.

  • [38, 27, 43, 3, 9, 82, 10] splits into [38, 27, 43, 3] and [9, 82, 10]
  • [38, 27, 43, 3] splits into [38, 27] and [43, 3]
  • [9, 82, 10] splits into [9] and [82, 10]
  • [38, 27] splits into [38] and [27]
  • [43, 3] splits into [43] and [3]
  • [82, 10] splits into [82] and [10]

Now every piece is a single element, which means every piece is already sorted. Time to merge.

Phase 2: Merge Back Together

This is where the sorting actually happens.

  • Merge [38] and [27] to get [27, 38]
  • Merge [43] and [3] to get [3, 43]
  • Merge [82] and [10] to get [10, 82]
  • Merge [27, 38] and [3, 43] to get [3, 27, 38, 43]
  • Merge [9] and [10, 82] to get [9, 10, 82]
  • Merge [3, 27, 38, 43] and [9, 10, 82] to get [3, 9, 10, 27, 38, 43, 82]

Done. The list is sorted.

How the Merge Step Actually Works

The merge step is the heart of the algorithm, so let's slow down and look at one example. Say we are merging [3, 27, 38, 43] and [9, 10, 82].

Put one finger at the start of each list. Compare the two items your fingers are pointing at, take the smaller one, and move that finger forward. Repeat.

  1. Compare 3 and 9. Take 3.
  2. Compare 27 and 9. Take 9.
  3. Compare 27 and 10. Take 10.
  4. Compare 27 and 82. Take 27.
  5. Compare 38 and 82. Take 38.
  6. Compare 43 and 82. Take 43.
  7. The left list is empty, so just add what is left: 82.

Result: [3, 9, 10, 27, 38, 43, 82]. Because both lists were already sorted, you never have to look backward. One pass, and you are done.

Merge Sort in Python (Full Code)

Here is a clean, beginner-friendly merge sort implementation in Python:

def merge_sort(arr):
    # Base case: a list with 0 or 1 items is already sorted
    if len(arr) <= 1:
        return arr

    # Divide: split the list in half
    mid = len(arr) // 2
    left_half = merge_sort(arr[:mid])
    right_half = merge_sort(arr[mid:])

    # Conquer: merge the two sorted halves
    return merge(left_half, right_half)


def merge(left, right):
    result = []
    i = j = 0

    # Compare items from both lists and take the smaller one
    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

    # One list is used up, so add whatever is left in the other
    result.extend(left[i:])
    result.extend(right[j:])
    return result


numbers = [38, 27, 43, 3, 9, 82, 10]
print(merge_sort(numbers))
# Output: [3, 9, 10, 27, 38, 43, 82]

Code Walkthrough

  • merge_sort keeps splitting the list until it reaches lists of size 1 (the base case), then hands the pieces to merge.
  • merge uses two pointers, i and j, one for each list. It always grabs the smaller of the two current items.
  • The <= comparison matters. When two values are equal, the one from the left list goes first, and that is what keeps merge sort stable (more on that below).
  • The two extend lines at the end handle leftovers once one list runs out.

If recursion still feels a bit fuzzy, do not worry. Trace the code with a tiny list like [4, 2, 1] on paper once, and it will click.

Merge Sort Time Complexity

This is the part that makes merge sort special.

CaseTime Complexity
Best caseO(n log n)
Average caseO(n log n)
Worst caseO(n log n)
Space complexityO(n)

Why O(n log n)?

Think about it in two parts:

  • How many times do we split? Each split cuts the list in half, so a list of n items can only be halved about log n times before we reach single items.
  • How much work does each level take? At every level, merging touches every element about once, which is roughly n work.

Multiply them together (n work per level, times log n levels) and you get O(n log n).

To put that in perspective, for one million items, an O(n²) algorithm like bubble sort needs around a trillion steps. Merge sort needs roughly 20 million. That gap is the whole reason merge sort exists.

The Catch: Space Complexity

Merge sort is not free. It needs extra memory, O(n), to hold the temporary lists created while merging. Insertion sort and selection sort sort the list "in place" and need almost no extra space. Merge sort trades memory for speed.

Is Merge Sort Stable?

Yes. Merge sort is a stable sorting algorithm, which means that if two items are equal, they stay in their original order after sorting.

Why does that matter? Say you have a list of students already sorted by name, and now you sort by grade. With a stable sort, students with the same grade stay in alphabetical order. With an unstable sort, that order can get scrambled. Stability is a big deal in real applications like spreadsheets, databases and user interfaces.

Merge Sort vs. Other Sorting Algorithms

Here is how merge sort stacks up against the sorts we have already covered:

AlgorithmBestAverageWorstSpaceStable?
Bubble SortO(n)O(n²)O(n²)O(1)Yes
Selection SortO(n²)O(n²)O(n²)O(1)No
Insertion SortO(n)O(n²)O(n²)O(1)Yes
Merge SortO(n log n)O(n log n)O(n log n)O(n)Yes

The takeaway: the first three are simple and great for learning, but merge sort is the one you would actually want for large data sets.

Merge Sort vs. Quick Sort

This is the question everyone asks. Both are O(n log n) on average, so which is better?

  • Merge sort guarantees O(n log n) every single time, is stable, and works beautifully on linked lists and huge files that do not fit in memory. The downside is the extra O(n) space.
  • Quick sort usually runs faster in practice and sorts in place, but its worst case is O(n²) and it is not stable.

There is no single winner. If you need guaranteed performance and stability, pick merge sort. If memory is tight and you want raw speed on average, quick sort often wins. We will cover quick sort in the next post of this series.

When Should You Use Merge Sort?

Merge sort is a great choice when:

  • You are sorting large data sets and need reliable O(n log n) performance.
  • You need a stable sort.
  • You are sorting linked lists, where merging is natural and needs no extra array space.
  • You are doing external sorting, meaning data too big to fit in RAM, like huge files sorted in chunks.
  • You want predictable behavior with no nasty worst-case surprises.

It is probably not the best pick when memory is very limited, or when your list is tiny. For small lists, even insertion sort can beat it because of lower overhead. In fact, many real-world sorting routines combine the two ideas. Python's built-in sort() uses Timsort, which blends merge sort and insertion sort.

Common Mistakes Beginners Make

A few things trip people up the first time:

  1. Forgetting the base case. Without if len(arr) <= 1: return arr, the recursion never stops and you get a stack overflow error.
  2. Using < instead of <= in the merge. Your code will still sort correctly, but it will no longer be stable.
  3. Forgetting leftovers. When one half runs out first, you still need to copy the remainder of the other half.
  4. Splitting wrongly. Always use integer division (//) for the midpoint, or Python will hand you a float and complain.

Merge Sort: Pros and Cons

Pros

  • Consistent O(n log n) in every case
  • Stable
  • Great for linked lists and external sorting
  • Easy to reason about once you see the pattern

Cons

  • Uses O(n) extra memory
  • Slower than simpler sorts on very small lists
  • Recursion can feel confusing at first

Frequently Asked Questions

What is merge sort in simple words?

Merge sort splits a list into smaller halves until each piece has one item, then merges those pieces back together in sorted order. It is a classic divide and conquer algorithm.

What is the time complexity of merge sort?

Merge sort runs in O(n log n) time in the best, average and worst cases, which makes it very predictable.

Is merge sort better than quick sort?

Not always. Merge sort has a guaranteed O(n log n) worst case and is stable, while quick sort is usually faster in practice and uses less memory but can degrade to O(n²) in the worst case.

Is merge sort in-place?

The standard version is not. It needs O(n) extra space for merging. In-place variants exist, but they are much more complicated.

Why is merge sort called divide and conquer?

Because it divides the problem into smaller subproblems, conquers each by sorting it recursively, and then combines the results.

Can merge sort be used on linked lists?

Yes, and it is often the preferred choice. Merging linked lists can be done without extra arrays, since you only need to rewire pointers.

Final Thoughts

Merge sort is the first algorithm in this series that really changes the game. Bubble, selection and insertion sort teach you the basics, but merge sort shows you how thinking differently (splitting a big problem into small ones) can turn a painfully slow process into a fast one.

If you remember just one thing, make it this: divide, conquer, merge.

Try it yourself. Take the Python code above, change the list, add a few print statements inside merge, and watch the pieces come together. Seeing it run is the fastest way to make it stick.

In the next post, we will tackle quick sort, merge sort's biggest rival. Make sure you have read the earlier guides on bubble sort, selection sort and insertion sort so you are ready for it.

Happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top