Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ The sorting workshop
EXPERIMENT 22 / 66

Divide. Sort. Recombine..

Merge sorted halves and account for the memory the implementation actually uses.

BY NAVAN SAMI◷ 9 MIN READCOREALGORITHM

01 Model the idea

Merge sort divides an input into smaller parts, sorts those parts, and merges them in order. Merging two sorted sequences takes linear work in their combined length. Across logarithmically many levels, the usual time bound is O(n log n). A Python implementation using slices and new lists also allocates storage; its practical costs include those copies.

THE THING THAT MUST STAY TRUE

Each merge output is sorted and contains exactly the consumed values.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
SPLIT the sequence into halves
SORT each half recursively
MERGE their smallest front candidates
APPEND any remaining suffix

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

merge_sort.py
def merge_sort(values):
    if len(values) <= 1: return list(values)
    middle = len(values) // 2
    left, right = merge_sort(values[:middle]), merge_sort(values[middle:])
    result, i, j = [], 0, 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
    return result + left[i:] + right[j:]
print(merge_sort([9, 2, 7, 2, 1]))
↳ EXPECTED OUTPUT
[1, 2, 2, 7, 9]
  1. 1

    The base case handles an empty or one-item sequence. Slicing makes each recursive subproblem explicit.

  2. 2

    The merge loop always takes the smaller front item. Taking the left item on equality preserves stability for the comparison used here.

  3. 3

    At most one side still has remaining values after the loop. Appending its suffix completes the result. Prefer sorted() in production unless you have a justified specialist requirement.

04 Count the cost

TIME

O(n log n)

SPACE

O(n) peak auxiliary plus O(log n) stack

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Write a merge function for two already-sorted integer lists.

Reveal one possible solution +
one_possible_solution.py
def merge(left, right):
    result, i, j = [], 0, 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
    return result + left[i:] + right[j:]
print(merge([1, 4], [2, 3, 5]))

06 Check your reasoning

QUICK SIGNAL CHECK

Why are the two inputs to merge required to be sorted?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.