Merge Sort
1 approach, code in every language
Problem description
Given an integer array nums, return an array that contains the same values arranged in non-decreasing order. You must produce the ordering yourself rather than delegating to a built-in sort routine.
A solution that compares every pair of elements is too slow for large inputs, so aim for an O(n log n) approach. Merge sort achieves this by splitting the array into halves, sorting each half, and stitching the two sorted halves back together.
Example 1
Input: nums = [5, 1, 4, 2, 8]
Output: [1, 2, 4, 5, 8]
The five values are reordered from smallest to largest.
Example 2
Input: nums = [3, -1, 3, 0]
Output: [-1, 0, 3, 3]
Duplicate values such as the two 3s remain in the result once each.
Constraints
1 <= nums.length <= 5 * 10^4-5 * 10^4 <= nums[i] <= 5 * 10^4
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free