Sort an Array

Medium Arrays & Hashing Merge Sort Like Approach Original on LeetCode

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.

00:00
Testcase

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.

ApproachTimeSpace
Brute force (insertion sort)O(n²)O(1)
Optimal (merge sort)O(n log n)O(n)

1Brute force (insertion sort)

TimeO(n²)A reverse-sorted array shifts 1 + 2 + … + (n - 1) elements.
SpaceO(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.

  1. For i from 1 to n - 1, save key = nums[i].
  2. Move j left from i - 1 while nums[j] > key, shifting nums[j] to nums[j + 1].
  3. 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;
    }
}

2Optimal (merge sort)

TimeO(n log n)log n levels of recursion, and each level merges n elements in total.
SpaceO(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.

  1. sort(lo, hi): if lo >= hi, return.
  2. mid = (lo + hi) / 2; sort(lo, mid); sort(mid + 1, hi).
  3. Merge: repeatedly take the smaller head of the two halves (left on ties) into tmp.
  4. Copy tmp[lo..hi] back into nums.
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];
    }
}

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.