Merge Sort
Sort by merging adjacent ordered runs. Start at width one and double the width after each pass.
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 aVisualizer
Step 1 of 19Inspect the current state
Select the smaller head from the two runs of width 1.
Variable watch
Step explanation
Select the smaller head from the two runs of width 1.
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 1
Two sorted queues send their lowest ticket number to a shared exit.Hint 2
Compare the first unused item of each run; only the smaller one can be the next output.Hint 3
Step 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?