Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Data Structures and Algorithms
  • What a Data Structure Is, and How Memory Works
  • Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
  • Linked Lists: A Chain of Clues, Built in Python
  • Stacks: Last In, First Out, With the Undo Button
  • Queues: First In, First Out, With a Ring of Cells
  • Hash Tables: The Name Tells You Where to Look
  • Binary Search Trees: Smaller Left, Bigger Right, Half Gone at Every Look
  • Tree Traversals: In-Order, Pre-Order and Post-Order as a Tour of the House
  • Heaps and Priority Queues: Most Urgent First, Without Searching the Room
  • Graphs and Breadth-First Search (BFS): Fewest Hops, Level by Level
  • Big-O: Reading Cost From Code, With Handshakes and a Guest Book
  • Recursion: Russian Dolls, the Base Case and the Call Stack
  • Linear vs Binary Search: Page by Page, or Open in the Middle
  • Insertion Sort: Take the Next Card and Slide It Left Until It Fits
  • Merge Sort: Split the Pile, Then Merge Two Sorted Piles
  • Quick Sort: Line Up Around One Friend, Then Repeat on Each Side
  • Depth-First Search (DFS): Go Deep, Back Up, Mark Where You've Been
  • The Two Pointers Technique: Find a Pair in One Pass Instead of Every Pair
  • The Sliding Window Technique: One In, One Out
  • Greedy Algorithms: The Best-Looking Choice, Right Now
  • Dynamic Programming: Work It Out Once, Write It Down, Read It Back
  1. Blog
  2. /
  3. Data Structures and Algorithms
  4. /
  5. Algorithms

Merge Sort: Split the Pile, Then Merge Two Sorted Piles

Ms Kate's eight exam papers sorted in 24 steps: split in half until each pile is one paper, then merge sorted piles by taking the lower top. A million papers take about 20 million steps, and the price is extra room.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Algorithms

What you will learn

  • Explain merging two sorted piles by always taking the lower top paper
  • Trace merge sort splitting down to single papers and merging back up
  • Say why merge sort costs O(n log n) whatever the input order
  • Explain the price of merge sort: a second place to work in

Before you start

  • Recursion
  • Insertion Sort

Ms Kate has marked eight exam papers, and they're in the order she marked them: 38, 27, 43, 3, 9, 82, 10, 55. She wants them in order of score. The same problem shows up for the whole school, with a million papers, and sorting a pile like that one paper at a time takes a lot of steps. Here, eight papers will be sorted in just twenty-four steps.

Two sorted piles

Imagine two piles of exam papers. Jack sorted one and Emma sorted the other, lowest score on top. Look at just the two top papers, 3 and 9. Take the lower one, 3, and put it on a new pile. Again: the tops are 27 and 9, so take 9. Then 27 and 10, take 10. You only ever look at two papers, and each paper is moved only once.

But where do sorted piles come from? Split the big pile in half, and again, and again, until each pile is just one paper. One paper on its own is always sorted. So: split until each pile is one paper, then merge the sorted piles back up. That's merge sort.

Split down, merge up

Merge sort on 38 27 43 3 9 82 10 55: split into halves down to single papers, then merge up to 27 38, 3 43, 9 82, 10 55, then 3 27 38 43 and 9 10 55 82, then the sorted pile 3 9 10 27 38 43 55 82 38 27 43 3 9 82 10 55 38 27 43 3 9 82 10 55 38 27 43 3 9 82 10 55 split down to piles of one 27 38 3 43 9 82 10 55 merge level 1: 8 steps 3 27 38 43 9 10 55 82 merge level 2: 8 steps 3 9 10 27 38 43 55 82 merge level 3: 8 steps = 24
Three levels of merging, eight papers placed on each level: 8 × 3 = 24 steps.

Split the pile in the middle: two piles of four. Split again: four piles of two. And again: eight piles of one, each sorted. Now merge: 38 and 27 become 27, 38. 43 and 3 become 3, 43. Those two become 3, 27, 38, 43. The right side goes the same way to 9, 10, 55, 82. The last merge turns two sorted piles of four into one.

The last merge, slowly

Two sorted piles, 3, 27, 38, 43 and 9, 10, 55, 82. Watch the top of each:

  1. 3 is lower than 9: take 3 from the left.
  2. 9 is lower than 27: take 9 from the right. Then 10.
  3. 27, 38 and 43 are each lower than 55: take them from the left.
  4. The left pile is empty, so take 55, then 82, from the right.

One sorted pile in eight steps, one step for every paper placed.

The code

import merger

show = True


def sort(papers):
    n = len(papers)
    if n == 1:
        return papers  # one paper is sorted
    mid = n // 2
    left = sort(papers[:mid])
    right = sort(papers[mid:])
    pile = merger.merge(left, right)
    if show:
        print(f"{left} + {right} = {pile}")
    return pile

One paper is already sorted, so hand it back. Otherwise split in the middle and sort each half. sort calls itself, once for the left half and once for the right. Then merge the two sorted halves.

steps = 0


def merge(left, right):
    global steps
    pile = [0] * (len(left) + len(right))
    i, j = 0, 0
    for k in range(len(pile)):
        steps += 1
        if (j == len(right)
                or (i < len(left) and left[i] <= right[j])):
            pile[k] = left[i]  # take from the left pile
            i += 1
        else:
            pile[k] = right[j]  # take from the right pile
            j += 1
    return pile

A new pile with room for both, and i and j point at the top paper of each. One loop for every place in the new pile, one step each. If the right pile is empty, or the left top is lower or equal, take from the left; otherwise take from the right. Only the two top papers are ever compared.

import merge_sort
import merger

scores = [38, 27, 43, 3, 9, 82, 10, 55]
merge_sort.sort(scores)
print("Steps: " + str(merger.steps))
[38] + [27] = [27, 38]
[43] + [3] = [3, 43]
[27, 38] + [3, 43] = [3, 27, 38, 43]
[9] + [82] = [9, 82]
[10] + [55] = [10, 55]
[9, 82] + [10, 55] = [9, 10, 55, 82]
[3, 27, 38, 43] + [9, 10, 55, 82] = [3, 9, 10, 27, 38, 43, 55, 82]
Steps: 24

A million papers

import random
import merge_sort
import merger

merge_sort.show = False
for n in (1_000, 10_000, 100_000, 1_000_000):
    scores = [random.randint(0, 100) for _ in range(n)]
    merger.steps = 0
    merge_sort.sort(scores)
    nn = n * n
    print(f"{n:9,d} papers: {merger.steps:,d} steps (n x n {nn:,d})")
    1,000 papers: 9,976 steps (n x n 1,000,000)
   10,000 papers: 133,616 steps (n x n 100,000,000)
  100,000 papers: 1,668,928 steps (n x n 10,000,000,000)
1,000,000 papers: 19,951,424 steps (n x n 1,000,000,000,000)

Halving a million takes only twenty levels, and every level places a million papers: about twenty million steps. Putting every paper against every other paper would be up to about a million million. The scores are random, but the step count depends only on how many papers there are, because every merge places each paper exactly once.

Where it breaks: room

Merge sort doesn't care about the order of the papers. A messy pile, a pile in order or a pile backwards all take the same steps. A pile already in order is still split and merged the same way. The catch is room.

Take two sorted piles side by side in one row: 5, 8 and 6, 7. Merge them in the same row, with no new pile. 5 is lower than 6, so it goes in the first spot, where it already sits. Fine. Now 6 is lower than 8, so the 6 must go in the second spot. But the 8 is sitting there and isn't placed yet. The 6 goes in and the 8 is wiped out, and you can never get it back.

So a merge needs a second place to work in: a new row as big as both piles together. Then nothing is wiped out, and you fill the new row 5, 6, 7, 8. That's why merge builds a new pile. The price is extra room, one spot for every paper.

The cost

PartCost
Halving into levelslog n levels (3 for 8 papers, 20 for a million)
Merging one leveln steps, every paper placed once
Whole sort, any input orderO(n log n)
Extra roomO(n), a second place as big as the piles

Compare insertion sort, which is O(n²) on shuffled input, and quick sort, which works in place but depends on its pivot.

Where you meet merge sort

  • The sort button in a language: Java and Python sort their lists with a method built on merging.
  • A database sorting a huge table sorts small parts, then merges them, even when the table doesn't fit in memory.
  • A search joining many servers: each sends back a sorted list, and merging them gives one sorted list.
  • Sorting by name, then by city: merge sort keeps equal items in their old order, so the first sort isn't undone.

Try it yourself

Add two more scores to make ten papers, and predict the merge lines before you run it.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Data Structures and Algorithms · 15 of 21

Previous
Insertion Sort: Take the Next Card and Slide It Left Until It Fits
Next post
Quick Sort: Line Up Around One Friend, Then Repeat on Each Side

Related courses on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Data Structures and Algorithms Concepts: No Coding Needed

How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)

Related posts

Big-O: Reading Cost From Code, With Handshakes and a Guest Book

Big-O asks one question: how do the steps grow when the list grows? Check a school trip sheet for duplicates two ways, handshakes and a guest book, count every step in Python, then grow the list to ten thousand ids and watch 10,000 steps turn into almost 50 million.

Recursion: Russian Dolls, the Base Case and the Call Stack

Recursion means doing the same job on a smaller piece of the problem, and stopping at a base case. Count Emma's Russian dolls with a Python function that calls itself, watch each call wait on the call stack so the answers come back in reverse, then take the base case out and meet RecursionError.

Linear vs Binary Search: Page by Page, or Open in the Middle

Is kite a real word? Page by page takes 11 checks; opening in the middle takes 4. Trace binary search step by step, see a million words answered in 20 checks, and watch it give the wrong answer on an unsorted list.

Insertion Sort: Take the Next Card and Slide It Left Until It Fits

Emma's hand 7, 3, 9, 2, 5 sorted one card at a time in 6 shifts. Trace each card, see why a backwards hand costs the most, why 5,000 shuffled cards need over 6 million shifts, and why a sorted hand needs zero.

On this page

  • Two sorted piles
  • Split down, merge up
  • The last merge, slowly
  • The code
  • A million papers
  • Where it breaks: room
  • The cost
  • Where you meet merge sort
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related courses on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Data Structures and Algorithms Concepts: No Coding Needed

How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.