Skip to contentKEEP THE CRAFTTHE SANCTUARY

Merge Sort

Trust two sorted child runs, merge their smallest unconsumed fronts, and keep left-before-right equality for stability. Distinguish a single linear merge from the complete logarithmic-level sorting workflow.

1 practice exercise2 interview problems

Recognize it when Stable ordering is required for equal-key records.

Checking your account…

Merge Sort Code Labs

Split Until Single Items

Merge sort recursively divides a range until each run has length zero or one, which is already sorted. Balanced splitting creates logarithmic recursion depth.

Merge Two Sorted Contracts

Given two sorted runs, repeatedly take the smaller front. When one run empties, append the remaining suffix of the other; no later comparison can change its order.

Trace One Merge Pass

Reference
def merge_pass(values,width):
    result=[]
    for start in range(0,len(values),2*width):
        left=values[start:start+width];right=values[start+width:start+2*width];i=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
Practice

Implement merge_pass(values,width). Merge adjacent sorted runs of width and return the new list. width must be a positive integer, and each input run must already be sorted.

Public tests

  • Merge every adjacent run pair

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace One Merge Pass

def merge_pass(values,width):
    result=[]
    for start in range(0,len(values),2*width):
        left=values[start:start+width];right=values[start+width:start+2*width];i=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

Merge One Run Pair and Keep the Tail

The existing pass Lab merges width-2 runs in [2,6,1,5,4]. Predict why the final 4 stays at the end: this is one bottom-up pass, not the complete sort.

Step Executed statement State Why
Slice runs left=values[start:start+width];right=values[start+width:start+2*width];i=j=0 left=[2, 6], right=[1, 5] Each width-2 run is already sorted.
Choose right front else:result.append(right[j]);j+=1 result=[1], j=1 1 is smaller than the left front 2.
Choose left front if left[i]<=right[j]:result.append(left[i]);i+=1 result=[1, 2], i=1 2 is now the smallest remaining front.
Drain first pair else:result.append(right[j]);j+=1; result.extend(left[i:]);result.extend(right[j:]) result=[1, 2, 5, 6] After taking 5, the remaining 6 must still be retained.
Odd tail result.extend(left[i:]);result.extend(right[j:]) result=[1, 2, 5, 6, 4] The final width-1 run has no partner. Another wider pass is needed for global order.
Print Output
print(merge_pass([2, 6, 1, 5, 4], 2)) [1, 2, 5, 6, 4]

The stable record Lab adds recursive levels and compares only record keys. Explain both permutation preservation and tie order; sorted values alone cannot prove stability.

Preserve Stability on Equality

Take from the left run when keys compare equal. That preserves original relative order across the split and makes merge sort stable.

Stable Merge Sort Records

Reference
def stable_merge_sort(records):
    if len(records)<2:return [item.copy() for item in records]
    mid=len(records)//2;left=stable_merge_sort(records[:mid]);right=stable_merge_sort(records[mid:]);result=[];i=j=0
    while i<len(left) and j<len(right):
        if left[i][0]<=right[j][0]:result.append(left[i]);i+=1
        else:result.append(right[j]);j+=1
    return result+left[i:]+right[j:]
Practice

Implement stable_merge_sort(records). Sort [key,label] records by key while preserving labels with equal keys.

Public tests

  • Take left first on equal keys

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Stable Merge Sort Records

def stable_merge_sort(records):
    if len(records)<2:return [item.copy() for item in records]
    mid=len(records)//2;left=stable_merge_sort(records[:mid]);right=stable_merge_sort(records[mid:]);result=[];i=j=0
    while i<len(left) and j<len(right):
        if left[i][0]<=right[j][0]:result.append(left[i]);i+=1
        else:result.append(right[j]);j+=1
    return result+left[i:]+right[j:]

Count Time and Auxiliary Space

The recurrence is two half-size sorts plus linear merging, yielding O(n log n). Standard list implementations use O(n) auxiliary merge storage and O(log n) call stack; Python slicing adds copies unless ranges are passed by index.

Explain It in an Interview

Say: “Each recursive call returns a sorted run. The merge chooses the smallest remaining front and takes left on equality for stability.” State base case, recurrence, copying policy, and why worst-case time remains O(n log n).

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Merge two sorted lists

Take the smaller head, step that side; when one runs out, copy the rest.

Two inputs are already sorted and you need one sorted result, or you walk both in step.

Trigger words

  • merge two sorted arrays
  • merge sort
  • sort an array
  • intersection of sorted
  • walk two lists in step
def merge(a, b):                     # a and b are sorted
    i, j = 0, 0
    merged = []
    while i < len(a) and j < len(b):
        if a[i] <= b[j]:             # <= keeps equal items in their original order
            merged.append(a[i])
            i += 1
        else:
            merged.append(b[j])
            j += 1
    merged.extend(a[i:])             # one side is used up;
    merged.extend(b[j:])             # copy what is left of the other
    return merged

Spot it when

  • 'Merge two sorted arrays/lists', 'merge sort'.
  • Intersections or differences of two sorted lists.

Remember

  • Each step moves exactly one pointer, so the merge is O(len(a) + len(b)).
  • Taking from the left list on ties (<=) makes the merge stable.

How problems bend it

  • Merge sort: Split the list in half, sort each half the same way, then merge the two sorted halves with this template.
  • Merge into the first array in place: Fill from the back: compare the largest remaining items and write them at the end.
  • Linked lists: Same loop on nodes, building the result after a dummy head.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Merge n and m itemsO(n + m)O(n + m)Includes copying the remaining suffix.
Complete merge sortO(n log n)O(n log n)Linear total merging at each balanced level.

Space

O(n) peak merge/copy storage plus O(log n) call frames for the full Lab; output is separate from constant pointer state.

Assumptions

  • Slicing allocates copies, but balanced levels still perform O(n log n) total copying.
  • The merge-pass trace is one pass, not a completely sorted output unless its run width covers the input.

Invariants Worth Saying Aloud

  1. The output prefix contains exactly the consumed values in sorted order.
  2. The two pointers identify the smallest unconsumed candidates.
  3. Taking the left equal key preserves its earlier position across a split.

When To Use Or Avoid Merge Sort

Use It When

  • Use merge sort when worst-case O(n log n) comparison work and stable ties matter.
  • Use a single merge when the inputs are already sorted.

Choose Another Tool When

  • A plain array implementation needs auxiliary storage; choose another approach if that memory is unavailable.
  • For ordinary Python tasks, sorted already provides a maintained stable implementation.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Merging unsorted fronts

If [4,1] is treated as a sorted run, taking the minimum current front can emit 2 before 1. The merge proof has already failed.

Prevent it: Establish sorted child runs before merging.

Avoid

front = min(left[0], right[0])

Use instead

front = min(sorted(left)[0], right[0])

Taking the right record on equal keys

The record in the left run originally came first. A strict < check selects the right equal record first and loses stability.

Prevent it: Use <= when selecting between equal-key fronts.

Avoid

picked = left if left[0] < right[0] else right

Use instead

picked = left if left[0] <= right[0] else right

Discarding an unconsumed suffix

Once right is exhausted, left may still contain values. Returning the prefix alone loses records.

Prevent it: Append each remaining suffix exactly once.

Avoid

result = prefix

Use instead

result = prefix + left[i:] + right[j:]

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.