Given an array of integers nums, sort the array in ascending order and return it.

You must solve the problem without using any built-in functions in O(n log n) time complexity and with the smallest space complexity possible.

Input & Output

Example 1 — Basic Sorting
$ Input: nums = [5,2,8,6,1,9,4]
Output: [1,2,4,5,6,8,9]
💡 Note: Sort the array in ascending order: all elements arranged from smallest to largest
Example 2 — Already Sorted
$ Input: nums = [1,2,3,4,5]
Output: [1,2,3,4,5]
💡 Note: Array is already sorted, return as is
Example 3 — Reverse Order
$ Input: nums = [5,4,3,2,1]
Output: [1,2,3,4,5]
💡 Note: Array in reverse order, needs complete reordering to ascending

Constraints

  • 1 ≤ nums.length ≤ 5 × 104
  • -5 × 104 ≤ nums[i] ≤ 5 × 104

Visualization

Tap to expand
Sort an Array - Merge Sort Algorithm INPUT Unsorted Array: 5 2 8 6 1 9 4 0 1 2 3 4 5 6 Divide Phase: [5,2,8,6,1,9,4] [5,2,8,6] [1,9,4] [5,2] [8,6] [1,9] [4] nums = [5,2,8,6,1,9,4] n = 7 elements Need: O(n log n) sort MERGE SORT STEPS 1 DIVIDE Split array in half mid = (lo+hi)/2 2 RECURSE Sort left and right halves mergeSort(left, right) 3 MERGE Combine sorted halves Compare and merge 4 BASE CASE Single element is sorted if (len <= 1) return Merge Example: [2,5,6,8] [1,4,9] [1,2,4,5,6,8,9] FINAL RESULT Sorted Array (Ascending): 1 2 4 5 6 8 9 OK - SORTED Complexity Analysis Time: O(n log n) Space: O(n) Stable: Yes Output: [1,2,4,5,6,8,9] Array sorted in ascending order using merge sort Key Insight: Merge Sort achieves O(n log n) by recursively dividing the array (log n levels) and merging sorted halves (O(n) per level). The divide-and-conquer approach ensures consistent performance regardless of input order, unlike QuickSort which can degrade to O(n^2) in worst case. TutorialsPoint - Sort an Array | Merge Sort Approach
Asked in
Amazon 15 Microsoft 12 Google 8 Facebook 6
85.0K Views
High Frequency
~15 min Avg. Time
2.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen