Merge Sorting
Pattern: Basic sorts
Split the array in half, sort each half with the same method, then merge the two sorted halves by repeatedly taking the smaller front element.
The problem
You are given an array of between 1 and 1500 whole numbers. Sort it in increasing order using merge sort, and return it.
For example, [5, 2, 4, 1] becomes [1, 2, 4, 5].
On the original site the problem is written a little differently, so use the link above for its exact wording. The
function name mergeSort and the limits are this guide's own.
Think first
- You have two sorted piles of cards face up. How do you combine them into one sorted pile, looking only at the top cards?
- If you can merge two sorted halves, how do you get the halves sorted in the first place?
- What is the smallest piece that is sorted without any work?
Hints
Brute force, and why it fails
The O(n²) sorts (selection, bubble, insertion) need about a million steps for 1500 elements, which is fine here, but about 10¹² for a million elements. Merge sort does about n log₂ n steps, roughly 20 million for a million elements, whatever the input looks like.
The key insight
Merging two sorted lists takes one pass. Halving the array again and again gives about log₂ n levels, and each level merges n elements in total, so the whole sort is O(n log n).
Dry run
| parts | [5] [2] [4] [1] |
|---|
nums = [5, 2, 4, 1]. Split into [5, 2] and [4, 1], then split again until every part has one element. A single element is already sorted.
The plan
function sort(nums, low, high):
if low >= high:
return # 0 or 1 element
mid = low + (high - low) div 2
sort(nums, low, mid)
sort(nums, mid + 1, high)
merge(nums, low, mid, high)
function merge(nums, low, mid, high):
merged = empty list
left = low, right = mid + 1
while left <= mid and right <= high:
if nums[left] <= nums[right]:
append nums[left] to merged, left = left + 1
else:
append nums[right] to merged, right = right + 1
append any leftovers from either side
copy merged back into nums[low..high]
Complexity
- Time
O(n log n)- Space
O(n)
About log₂ n levels with O(n) merging each. The temporary lists use O(n) memory, and the recursion is about log₂ n deep.
Edge cases
- One element: the base case returns at once.
- Already sorted or reversed: still O(n log n). Merge sort does not care about the input order.
- Many equal values:
<=takes the left one first, so equal values keep their order. - Odd lengths: the left half gets the extra element, which works fine.
I've built my logic, show the code
Java
class Solution {
public int[] mergeSort(int[] nums) {
sort(nums, 0, nums.length - 1);
return nums;
}
private void sort(int[] nums, int low, int high) {
if (low >= high) {
return; // 0 or 1 element is already sorted
}
int mid = low + (high - low) / 2;
sort(nums, low, mid); // sort the left half
sort(nums, mid + 1, high); // sort the right half
merge(nums, low, mid, high); // combine the two sorted halves
}
private void merge(int[] nums, int low, int mid, int high) {
int[] merged = new int[high - low + 1];
int left = low;
int right = mid + 1;
int k = 0;
while (left <= mid && right <= high) {
if (nums[left] <= nums[right]) {
merged[k++] = nums[left++];
} else {
merged[k++] = nums[right++];
}
}
while (left <= mid) {
merged[k++] = nums[left++];
}
while (right <= high) {
merged[k++] = nums[right++];
}
for (int i = 0; i < merged.length; i++) {
nums[low + i] = merged[i];
}
}
}C++
class Solution {
public:
vector<int> mergeSort(vector<int>& nums) {
sort(nums, 0, static_cast<int>(nums.size()) - 1);
return nums;
}
void sort(vector<int>& nums, int low, int high) {
if (low >= high) {
return; // 0 or 1 element is already sorted
}
int mid = low + (high - low) / 2;
sort(nums, low, mid); // sort the left half
sort(nums, mid + 1, high); // sort the right half
merge(nums, low, mid, high); // combine the two sorted halves
}
void merge(vector<int>& nums, int low, int mid, int high) {
vector<int> merged;
merged.reserve(high - low + 1);
int left = low;
int right = mid + 1;
while (left <= mid && right <= high) {
if (nums[left] <= nums[right]) {
merged.push_back(nums[left++]);
} else {
merged.push_back(nums[right++]);
}
}
while (left <= mid) {
merged.push_back(nums[left++]);
}
while (right <= high) {
merged.push_back(nums[right++]);
}
for (int i = 0; i < static_cast<int>(merged.size()); i++) {
nums[low + i] = merged[i];
}
}
};Python
class Solution:
def mergeSort(self, nums):
self.sort(nums, 0, len(nums) - 1)
return nums
def sort(self, nums, low, high):
if low >= high:
return # 0 or 1 element is already sorted
mid = (low + high) // 2
self.sort(nums, low, mid) # sort the left half
self.sort(nums, mid + 1, high) # sort the right half
self.merge(nums, low, mid, high) # combine the two sorted halves
def merge(self, nums, low, mid, high):
merged = []
left, right = low, mid + 1
while left <= mid and right <= high:
if nums[left] <= nums[right]:
merged.append(nums[left])
left += 1
else:
merged.append(nums[right])
right += 1
merged.extend(nums[left:mid + 1])
merged.extend(nums[right:high + 1])
nums[low:high + 1] = mergedCommon mistakes
- Forgetting to copy the leftovers after one side runs out.
- Copying
mergedback to index 0 instead of indexlow. - Using
(low + high) / 2with huge indexes in Java or C++, where the sum can overflow.low + (high - low) / 2is safe. - Using
<instead of<=, which still sorts but loses stability.