Sort An Array Problem
Description
LeetCode Problem 912.
Given an array of integers nums, sort the array in ascending order.
Example 1:
Input: nums = [5,2,3,1]
Output: [1,2,3,5]
Example 2:
Input: nums = [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]
Constraints:
- 1 <= nums.length <= 5 * 10^4
- -5 * 10^4 <= nums[i] <= 5 * 10^4
Solution
Approach: Merge Sort
Simple sorts such as insertion sort take O(n2) time, which is too slow for 5 · 104 numbers. Merge sort runs in O(n log n) in every case, including sorted input and many duplicates, where a quick sort with a poor pivot choice can degrade to O(n2).
Merge sort is divide and conquer:
- Split the range
nums[lo..hi]in the middle atmid. - Sort the left half
nums[lo..mid]and the right halfnums[mid+1..hi]recursively. A range of one element is already sorted. - Merge the two sorted halves: repeatedly compare the front of each half and copy the smaller value into a buffer. When one half runs out, copy the rest of the other. Then copy the buffer back into
nums[lo..hi].
[5, 2, 3, 1]
split -> [5, 2] [3, 1]
sort -> [2, 5] [1, 3]
merge -> [1, 2, 3, 5]
Allocate one buffer of length n up front and reuse it for every merge, instead of creating new arrays at each level. Comparing with <= takes from the left half on ties, which makes the sort stable.
Complexity: O(n log n) time, where n is the length of nums: there are log n levels of splitting and each level merges n elements in total. O(n) extra space for the buffer, plus O(log n) for the recursion.
class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
buffer = [0] * len(nums) # scratch space shared by every merge
def merge_sort(lo, hi):
"""Sort nums[lo..hi] in place."""
if lo >= hi:
return
mid = (lo + hi) // 2
merge_sort(lo, mid)
merge_sort(mid + 1, hi)
# Merge the sorted halves nums[lo..mid] and nums[mid+1..hi] into buffer.
i, j, k = lo, mid + 1, lo
while i <= mid and j <= hi:
if nums[i] <= nums[j]: # "<=" keeps equal values in order (stable)
buffer[k] = nums[i]
i += 1
else:
buffer[k] = nums[j]
j += 1
k += 1
while i <= mid:
buffer[k] = nums[i]
i += 1
k += 1
while j <= hi:
buffer[k] = nums[j]
j += 1
k += 1
nums[lo:hi + 1] = buffer[lo:hi + 1]
merge_sort(0, len(nums) - 1)
return nums
Now write it from memory
Close the write-up and solve it yourself against the tests.