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.
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.
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
Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Merge Sort proof does not depend on a minor Python release.