Sort an Array
Sort an Array is a medium arrays & hashing problem solved with the merge sort like approach pattern.
The best approach, optimal (merge sort), runs in O(n log n) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (insertion sort) up.
Problem
Given an integer array nums, return it sorted in non-decreasing order.
Write the sorting algorithm yourself instead of calling a library sort. Your solution should run in O(n log n) time and use as little extra space as you reasonably can.
Examples
Example 1
- Input
nums = [7, -2, 4, 4, 0]- Output
[-2, 0, 4, 4, 7]- Why
- Values in non-decreasing order; the two 4s stay next to each other.
Example 2
- Input
nums = [3, 1, 2]- Output
[1, 2, 3]- Why
- A small unsorted array.
Example 3
- Input
nums = [9]- Output
[9]- Why
- One element is already sorted.
Constraints
1 <= nums.length <= 5 * 10^4-5 * 10^4 <= nums[i] <= 5 * 10^4- Do not call a built-in sort; aim for O(n log n) time.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 10 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (insertion sort) | O(n²) | O(1) |
| Optimal (merge sort) | O(n log n) | O(n) |
1Brute force (insertion sort)
O(n²)A reverse-sorted array shifts 1 + 2 + … + (n - 1) elements.O(1)Sorts in place with one saved value.Grow a sorted prefix one element at a time: take the next element and shift larger elements of the prefix one step right until its place is found.
- For i from 1 to n - 1, save
key = nums[i]. - Move j left from i - 1 while
nums[j] > key, shiftingnums[j]tonums[j + 1]. - Write key at
j + 1.
class Solution {
public int[] sortArray(int[] nums) {
for (int i = 1; i < nums.length; i++) {
int key = nums[i], j = i - 1;
while (j >= 0 && nums[j] > key) {
nums[j + 1] = nums[j];
j--;
}
nums[j + 1] = key;
}
return nums;
}
}class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
for i in range(1, len(nums)):
key, j = nums[i], i - 1
while j >= 0 and nums[j] > key:
nums[j + 1] = nums[j]
j -= 1
nums[j + 1] = key
return numsclass Solution {
public:
vector<int> sortArray(vector<int>& nums) {
for (int i = 1; i < (int)nums.size(); i++) {
int key = nums[i], j = i - 1;
while (j >= 0 && nums[j] > key) {
nums[j + 1] = nums[j];
j--;
}
nums[j + 1] = key;
}
return nums;
}
};function sortArray(nums) {
for (let i = 1; i < nums.length; i++) {
const key = nums[i];
let j = i - 1;
while (j >= 0 && nums[j] > key) {
nums[j + 1] = nums[j];
j--;
}
nums[j + 1] = key;
}
return nums;
}2Optimal (merge sort)
O(n log n)log n levels of recursion, and each level merges n elements in total.O(n)One buffer of size n plus O(log n) recursion stack.Divide and conquer: sort the left half and the right half recursively, then merge the two sorted halves with two pointers into a shared buffer and copy back. The split is always balanced, so the running time is O(n log n) on every input, including sorted and all-equal arrays.
- sort(lo, hi): if lo >= hi, return.
- mid = (lo + hi) / 2; sort(lo, mid); sort(mid + 1, hi).
- Merge: repeatedly take the smaller head of the two halves (left on ties) into
tmp. - Copy
tmp[lo..hi]back intonums.
class Solution {
private int[] tmp;
public int[] sortArray(int[] nums) {
tmp = new int[nums.length];
sort(nums, 0, nums.length - 1);
return nums;
}
private void sort(int[] a, int lo, int hi) {
if (lo >= hi) return;
int mid = (lo + hi) >>> 1;
sort(a, lo, mid);
sort(a, mid + 1, hi);
int i = lo, j = mid + 1, k = lo;
while (i <= mid && j <= hi) tmp[k++] = a[i] <= a[j] ? a[i++] : a[j++];
while (i <= mid) tmp[k++] = a[i++];
while (j <= hi) tmp[k++] = a[j++];
for (k = lo; k <= hi; k++) a[k] = tmp[k];
}
}class Solution:
def sortArray(self, nums: List[int]) -> List[int]:
tmp = [0] * len(nums)
def sort(lo: int, hi: int) -> None:
if lo >= hi:
return
mid = (lo + hi) // 2
sort(lo, mid)
sort(mid + 1, hi)
i, j, k = lo, mid + 1, lo
while i <= mid and j <= hi:
if nums[i] <= nums[j]:
tmp[k] = nums[i]
i += 1
else:
tmp[k] = nums[j]
j += 1
k += 1
while i <= mid:
tmp[k] = nums[i]
i += 1
k += 1
while j <= hi:
tmp[k] = nums[j]
j += 1
k += 1
nums[lo:hi + 1] = tmp[lo:hi + 1]
sort(0, len(nums) - 1)
return numsclass Solution {
public:
vector<int> sortArray(vector<int>& nums) {
tmp.assign(nums.size(), 0);
sortRange(nums, 0, (int)nums.size() - 1);
return nums;
}
private:
vector<int> tmp;
void sortRange(vector<int>& a, int lo, int hi) {
if (lo >= hi) return;
int mid = lo + (hi - lo) / 2;
sortRange(a, lo, mid);
sortRange(a, mid + 1, hi);
int i = lo, j = mid + 1, k = lo;
while (i <= mid && j <= hi) tmp[k++] = a[i] <= a[j] ? a[i++] : a[j++];
while (i <= mid) tmp[k++] = a[i++];
while (j <= hi) tmp[k++] = a[j++];
for (k = lo; k <= hi; k++) a[k] = tmp[k];
}
};function sortArray(nums) {
const tmp = new Array(nums.length);
const sort = (lo, hi) => {
if (lo >= hi) return;
const mid = (lo + hi) >> 1;
sort(lo, mid);
sort(mid + 1, hi);
let i = lo, j = mid + 1, k = lo;
while (i <= mid && j <= hi) tmp[k++] = nums[i] <= nums[j] ? nums[i++] : nums[j++];
while (i <= mid) tmp[k++] = nums[i++];
while (j <= hi) tmp[k++] = nums[j++];
for (k = lo; k <= hi; k++) nums[k] = tmp[k];
};
sort(0, nums.length - 1);
return nums;
}Edge cases to test
- Single element
- Already sorted or reverse sorted input (worst case for naive quicksort)
- Many duplicates or all values equal
- Negative values
Hints
Hint 1
Simple quadratic sorts work for small inputs but are too slow for 5 * 10^4 elements.
Hint 2
Split the array in half, sort each half, then merge two sorted halves in linear time.
Hint 3
Reuse one temporary buffer for every merge instead of allocating new arrays.
FAQ
What is the best time complexity for Sort an Array?
Optimal (merge sort) runs in O(n log n) time and O(n) extra space. log n levels of recursion, and each level merges n elements in total.
Which pattern does Sort an Array use?
It is a arrays & hashing problem that uses the merge sort like approach pattern. Other problems with the same pattern: Count Inversions, Arranging the array, Reverse Pairs.
Is there a brute force solution for Sort an Array?
Yes. Brute force (insertion sort) takes O(n²) time and O(1) space. Grow a sorted prefix one element at a time: take the next element and shift larger elements of the prefix one step right until its place is found.
Which edge cases should I test for Sort an Array?
Single element; Already sorted or reverse sorted input (worst case for naive quicksort); Many duplicates or all values equal; Negative values.