Workspace Merge Sort
0d
DSA Problem Sheet

Merge Sort

Sort by merging adjacent ordered runs. Start at width one and double the width after each pass.

EXECUTION LAB

Sort by merging adjacent ordered runs. Start at width one and double the width after each pass.

Input and constraints
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
a = values.copy()
buf = [0] * (len(a))
width = 1
while (width < len(a)):
start = 0
while (start < len(a)):
mid = min((start + width), len(a))
end = min(((start + width) + width), len(a))
left = start
right = mid
out = start
while (out < end):
if ((left < mid) and ((right >= end) or (a[left] <= a[right]))):
buf[out] = a[left]
left = (left + 1)
else:
buf[out] = a[right]
right = (right + 1)
out = (out + 1)
start = end
a = buf.copy()
width = (width * 2)
return a

Visualizer

Step 1 of 19
08left, out
12right
27
34
41

Inspect the current state

Select the smaller head from the two runs of width 1.

Variable watch

left 0right 1out 0width 1buf [0,0,0,0,0]

Step explanation

Select the smaller head from the two runs of width 1.

comparisons 3reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(n log n) time · O(n) space

Worked explanation

Two sorted queues send their lowest ticket number to a shared exit.

Guided solution

Compare the first unused item of each run; only the smaller one can be the next output.

O(n log n) time · O(n) auxiliary space

Examples

Worked example · {"values":[8,2,7,4,1],"target":0} ⇒ [1,2,4,7,8]

Edge case 1 · {"values":[],"target":0} ⇒ []

Edge case 2 · {"values":[3,1,3],"target":0} ⇒ [1,3,3]

Progressive hints

Hint 1Two sorted queues send their lowest ticket number to a shared exit.
Hint 2Compare the first unused item of each run; only the smaller one can be the next output.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

A partial run near the end still needs copying into the output.

Interview follow-up

Why does taking the left item on equality preserve stability?