Continue learning
Practice related DSA questions in the same topic.
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.
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 aSelect the smaller head from the two runs of width 1.
Select the smaller head from the two runs of width 1.
Two sorted queues send their lowest ticket number to a shared exit.
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
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]
A partial run near the end still needs copying into the output.
Why does taking the left item on equality preserve stability?