Foundation · Module 4 · Lesson 4

Merge Sort

Divide, recursively sort, and merge stable runs.

15–25 min readLesson 22 of 123 Interactive Lab

Lesson 22 of 123

1d streak

Interactive Visualization

Trace the algorithm state by state

Change the inputs, run an operation, and connect each visible state change to the explanation below.

Interactive algorithm lab

Merge Sort

Split into runs, then merge in sorted order

Step 1 / 17

Input size

6

Active cells

6

Ranges

1

Progress

1/17

8
0
3
1
6
2
2
3
7
4
1
5
range [0, 5]

Why this step happens

Divide indexes 0…5 around the middle.

Invariant to protect

Every recursive call is responsible for sorting exactly its own range.

Theory lesson · Step-by-step

Understand Merge Sort

Divide, recursively sort, and merge stable runs.

Worked approach

Trace the reasoning step by step

  1. 1Split the range around its middle.
  2. 2Recursively sort the left and right halves.
  3. 3Compare the front values of both sorted halves.
  4. 4Copy the smaller value and append any remainder.

Concrete example

Sort [4, 1, 3, 2] by divide and merge.

  1. 1Split into [4,1] and [3,2].
  2. 2Sort halves to [1,4] and [2,3].
  3. 3Merge to [1,2,3,4].

Balanced splitting gives O(n log n) time.

What must remain true (Loop Invariant)

Each recursive call returns a sorted range; merging preserves order while consuming both halves.

Cost Model

Complexity & Trade-offs

Sort
O(n log n)
O(n)
Include stability and input shape when comparing sorts.

When to use it

  • Creating order before searching, grouping, deduplicating, or scanning.
  • Selecting records using stability, memory, and input-shape constraints.
  • Turning pairwise decisions into monotonic scans.

Common mistakes

  • Comparing time alone while ignoring stability and auxiliary memory.
  • Breaking duplicate order when stability is required.
  • Quoting average performance without worst-case behavior.

Practice prompts

  • Reproduce the worked Merge Sort example without looking at the trace.
  • Change one input condition and explain whether the Merge Sort invariant still holds.
  • Implement the approach, derive its cost, and compare it with a straightforward baseline.

Mastery check

Can you derive it instead of memorizing it?

State the invariant before looking at code.
Explain why every transition is safe.
Construct a worst-case input.
Name one alternative and its trade-off.