Skip to main content

Sort an Array

Medium
Data Structures and Algorithms
Editorial
Topics:
Array
Sorting
Divide and Conquer

Given nums, an array of integers, arrange all of its elements in ascending order. Ascending order means each element is less than or equal to the element that follows it, so duplicate values remain present with the same frequency.

Return the sorted array. Do not call any built-in sorting function, and use an algorithm whose running time is O(n log n), where n is the length of nums.

The returned array must contain exactly the same integers as the input, including repeated values. An input with one element is already sorted.

Example 1:

Input: nums = [8,-3,4,4,1]
Output: [-3,1,4,4,8]
Explanation: The values are rearranged from smallest to largest, while both occurrences of 4 are retained.

Example 2:

Input: nums = [6,2,9,0,-5,3]
Output: [-5,0,2,3,6,9]
Explanation: Sorting the six values in nondecreasing order produces the returned array.

Example 3:

Input: nums = [7,7,7]
Output: [7,7,7]
Explanation: All values are equal, so their order does not change.

Constraints:

  • 1 <= nums.length <= 5 * 10^4
  • -5 * 10^4 <= nums[i] <= 5 * 10^4
  • ``nums is a JSON array of integers.
  • The input contains at least one integer.

Need help or want more practice?

Practise in an interviewGet AI Coach help