Stable Divide-and-Conquer Sort of an Integer List
Heaps, Sorting & SearchAuto-graded · 20 test casesLast updated
Sort a list of integers in ascending order without mutating the input, using a divide-and-conquer merge approach that guarantees O(n log n) time and linear auxiliary space.
Sort by Merging
Write a function that takes a list of integers and returns a new list containing the same values arranged from smallest to largest (non-decreasing order).
The intent is for you to build the sort yourself using a divide-and-conquer strategy, where sorted pieces are combined by merging, rather than relying on a built-in sort. Your approach should:
- run in
O(n log n)time for every input, including already ordered, reverse ordered, and all-equal inputs; - be stable: when two values are equal, the one that appeared earlier in the input must appear earlier in the output;
- use
O(n)auxiliary space.
The input list must not be modified. Return a fresh list, even when the input is empty or has a single element.
Input
values: a list of integers.
Output
- A new list with the elements of
valuessorted in non-decreasing order.
Edge cases
- An empty list returns an empty list.
- A single-element list returns a list with that element.
- Lists with all identical elements, or lists that are already sorted or sorted in reverse, must still be handled correctly.
Constraints
0 <= len(values) <= 10^5-10^9 <= values[i] <= 10^9- Target
O(n log n)time andO(n)auxiliary space.
Examples
Example 1
Input: stable_merge_sort([38, 27, 43, 3, 9, 82, 10])
Output: [3, 9, 10, 27, 38, 43, 82]
Example 2
Input: stable_merge_sort([5, 2, 5, 1])
Output: [1, 2, 5, 5]
Hints
Hint 1
Think of the list as many tiny sorted runs. A run of length 1 is already sorted, so the real work is combining two sorted runs into one.
Hint 2
To merge two sorted runs, keep one pointer at the front of each and repeatedly take the smaller front element. When the fronts are equal, take from the left run so equal elements keep their original order. Then append whatever is left in the other run.
Hint 3
You can recurse by splitting in halves, or iterate bottom-up by merging runs of width 1, 2, 4, and so on. In the iterative version, alternate between two buffers so you only allocate one extra array.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Merge sort rests on one fact: two sorted runs can be combined into one sorted run in linear time. Start with n runs of length 1, which are trivially sorted. Then repeatedly merge neighbouring runs so the run width goes 1, 2, 4, 8, ... until a single run covers the whole list. This is the bottom-up (iterative) form, and it needs no recursion.
Two buffers, src and dst, are used. Each pass reads sorted runs from src and writes the merged runs into dst. After the pass the buffers swap roles. This means only one extra array is allocated for the whole algorithm.
For each pass and each starting index left:
mid = min(left + width, n)right = min(left + 2 * width, n)
The clamps handle a ragged tail when n is not a power of two. If only a left block remains, mid and right both reach n, and the merge just copies it across.
The merge step uses pointers i (left run) and j (right run). While both runs have elements, it copies the smaller front element to dst; on a tie it takes the left one. Then it drains whichever run still has elements.
Why it is correct
- Invariant: at the start of each pass with width
w, every block of lengthwinsrc(the last may be shorter) is sorted. Forw = 1this is trivial. - Step: merging two sorted adjacent blocks yields a sorted block of up to
2welements, and every index belongs to exactly one block, sodstis completely written. After the swap the invariant holds for2w. - Termination: when
width >= n, the single block[0, n)is sorted, and thanks to the final swap it lives insrc, which is returned. - Stability: blocks being merged are adjacent, with the earlier elements in the left block, and ties are resolved with
<=so the left element goes first. Equal elements therefore never swap relative order. - No mutation: the algorithm works on a copy, so the caller's list is untouched.
Complexity
- Time:
O(n log n)always. There areceil(log2 n)passes and each pass doesO(n)work, regardless of input order. - Space:
O(n)auxiliary for the two buffers, with no recursion stack.
Reference solution
from typing import List
def stable_merge_sort(values: List[int]) -> List[int]:
n = len(values)
if n < 2:
return list(values)
src = list(values)
dst = [0] * n
width = 1
while width < n:
for left in range(0, n, 2 * width):
mid = min(left + width, n)
right = min(left + 2 * width, n)
i, j, k = left, mid, left
while i < mid and j < right:
if src[i] <= src[j]:
dst[k] = src[i]
i += 1
else:
dst[k] = src[j]
j += 1
k += 1
while i < mid:
dst[k] = src[i]
i += 1
k += 1
while j < right:
dst[k] = src[j]
j += 1
k += 1
src, dst = dst, src
width *= 2
return src