Sort an Array (LeetCode 912): Solution and Explanation
Sort an integer array in ascending order without a built-in sort. The array can hold 50,000 values, so the solution has to run in O(n log n).
Intuition
Bubble, insertion and selection sort are easy to write but do O(n²) work. At 50,000 elements that is over a billion steps, so they time out here.
Merging is the key cheap operation: two arrays that are already sorted can be combined into one sorted array in linear time. Keep a pointer at the front of each, repeatedly take the smaller front, and move that pointer forward.
So where do sorted arrays come from? Any single element is trivially sorted. Merge neighbouring singles and you have sorted runs of 2. Merge neighbouring 2s and you get runs of 4. After about log2(n) rounds of doubling, one run covers the whole array.
Each round touches every element once, and there are log2(n) rounds, which gives O(n log n). Doing it bottom-up with a loop over width avoids recursion entirely and needs just one scratch buffer.
Approach: Bottom-up merge sort
- Allocate a buffer
bufwith the same length asnums, and start withwidth = 1. - While
width < n, walkloacross the array in steps of2 * width. The left run is[lo, mid)withmid = lo + width, and the right run is[mid, hi)withhi = min(lo + 2 * width, n). - Merge with pointers
i(left) andj(right): write the smaller ofnums[i]andnums[j]intobuf[k], taking the left one on ties so equal values keep their order. - When one run is exhausted, copy the rest of the other run into the buffer. It is already sorted.
- Copy
buf[lo:hi]back intonums[lo:hi], then move to the next pair. - After the pass, double
width. Whenwidth >= n, the array is one sorted run; return it.
Step-by-step example
nums = [5,2,3,1]
- width = 1: runs are [5], [2], [3], [1].
- Merge [5] and [2]: 2 < 5, write 2, then copy the leftover 5. Positions 0 to 1 become [2,5].
- Merge [3] and [1]: 1 < 3, write 1, then copy 3. Positions 2 to 3 become [1,3]. The array is [2,5,1,3].
- width = 2: merge [2,5] with [1,3]. Take 1, then 2, then 3, then copy the leftover 5.
- The array is [1,2,3,5]. width becomes 4, which is not less than n, so return.
Code: Python, Java, C++
1class Solution:
2 def sortArray(self, nums: List[int]) -> List[int]:
3 n = len(nums)
4 buf = [0] * n
5 width = 1
6 while width < n:
7 for lo in range(0, n - width, 2 * width):
8 mid, hi = lo + width, min(lo + 2 * width, n)
9 i, j, k = lo, mid, lo
10 while i < mid and j < hi:
11 if nums[i] <= nums[j]:
12 buf[k] = nums[i]
13 i += 1
14 else:
15 buf[k] = nums[j]
16 j += 1
17 k += 1
18 buf[k:hi] = nums[i:mid] + nums[j:hi]
19 nums[lo:hi] = buf[lo:hi]
20 width *= 2
21 return nums1class Solution {
2 public int[] sortArray(int[] nums) {
3 int n = nums.length;
4 int[] buf = new int[n];
5 for (int width = 1; width < n; width *= 2) {
6 for (int lo = 0; lo + width < n; lo += 2 * width) {
7 int mid = lo + width, hi = Math.min(lo + 2 * width, n);
8 int i = lo, j = mid, k = lo;
9 while (i < mid && j < hi) {
10 if (nums[i] <= nums[j]) {
11 buf[k++] = nums[i++];
12 } else {
13 buf[k++] = nums[j++];
14 }
15 }
16 while (i < mid) buf[k++] = nums[i++];
17 while (j < hi) buf[k++] = nums[j++];
18 System.arraycopy(buf, lo, nums, lo, hi - lo);
19 }
20 }
21 return nums;
22 }
23}1class Solution {
2public:
3 vector<int> sortArray(vector<int>& nums) {
4 int n = nums.size();
5 vector<int> buf(n);
6 for (int width = 1; width < n; width *= 2) {
7 for (int lo = 0; lo + width < n; lo += 2 * width) {
8 int mid = lo + width, hi = min(lo + 2 * width, n);
9 int i = lo, j = mid, k = lo;
10 while (i < mid && j < hi) {
11 if (nums[i] <= nums[j]) {
12 buf[k++] = nums[i++];
13 } else {
14 buf[k++] = nums[j++];
15 }
16 }
17 while (i < mid) buf[k++] = nums[i++];
18 while (j < hi) buf[k++] = nums[j++];
19 copy(buf.begin() + lo, buf.begin() + hi, nums.begin() + lo);
20 }
21 }
22 return nums;
23 }
24};Time and space complexity
O(n log n)
Each pass over the array merges every element exactly once, which is O(n), and the run width doubles each pass, so there are about log2(n) passes.
O(n)
One buffer of length n holds merge output. The bottom-up version needs no recursion stack.
Other approaches
Top-down merge sort (time O(n log n), space O(n))
Split the array in half recursively, sort both halves, then merge. Same work and same buffer, plus O(log n) recursion depth.
Heap sort (time O(n log n), space O(1))
Build a max-heap in place, then repeatedly swap the root to the end and sift down. It uses O(1) extra space but is not stable and has poorer cache behaviour.
Counting sort (time O(n + k), space O(k))
Values lie in [-50000, 50000], so you can count occurrences in an array of 100,001 slots and rebuild the output. Linear time, but only because the value range is small.
Common mistakes
- Using quicksort with a fixed pivot. LeetCode includes already sorted and all-equal inputs that push it to O(n²) and time it out.
- Forgetting the leftovers after the two-pointer loop. One run always finishes first, and its partner's tail must still be copied.
- Computing
hiaslo + 2 * widthwithout capping atn. The last pair is often shorter than a full block. - Using
<instead of<=when comparing fronts. The answer is still sorted, but the sort loses stability.
Frequently asked questions
Why does the loop condition use lo + width < n?
A pair only needs merging when a right run exists. If lo + width >= n, the remaining block is a lone left run that is already sorted, so it can stay where it is.
Is merge sort stable?
Yes, as long as ties take the element from the left run. Equal values then keep their original relative order.
Why not just call the language's sort?
The problem forbids it. The point is to implement an O(n log n) algorithm yourself, and the built-in would also hide the merge step this problem is about.
Can merge sort be done without the O(n) buffer?
In-place merge variants exist but are complicated and slower in practice. If O(1) extra space matters, heap sort is the usual choice.