Merge Sort Implementation - Problem

Implement the merge sort algorithm from scratch to sort an array of integers in ascending order.

Your implementation should:

  • Display the array state at each merge step during the sorting process
  • Return the final sorted array
  • Use the divide-and-conquer approach typical of merge sort

The merge sort algorithm works by:

  1. Dividing the array into two halves recursively until single elements remain
  2. Merging the divided arrays back together in sorted order
  3. Combining results to produce the final sorted array

Input & Output

Example 1 — Basic Unsorted Array
$ Input: nums = [6,3,8,2]
Output: [2,3,6,8]
💡 Note: Merge sort divides [6,3,8,2] into [6,3] and [8,2], sorts each half to [3,6] and [2,8], then merges them into [2,3,6,8]
Example 2 — Already Sorted Array
$ Input: nums = [1,2,3,4]
Output: [1,2,3,4]
💡 Note: Even though the array is already sorted, merge sort still performs the divide and conquer process, resulting in the same sorted array
Example 3 — Reverse Sorted Array
$ Input: nums = [9,7,5,3,1]
Output: [1,3,5,7,9]
💡 Note: Worst case input where every merge step requires full comparison, but merge sort still achieves O(n log n) time

Constraints

  • 1 ≤ nums.length ≤ 104
  • -106 ≤ nums[i] ≤ 106

Visualization

Tap to expand
INPUTALGORITHMRESULT6382Unsorted ArrayLength: 4 elementsNeed to sort in ascending order1Divide array recursively2Base case: single elements3Merge sorted halves4Combine final result6,38,23,62,8Divide then merge process2368Sorted ArrayTime: O(n log n)Space: O(n)Key Insight:Merge sort guarantees O(n log n) performance by dividing the problemuntil trivially solvable, then efficiently merging sorted results.TutorialsPoint - Merge Sort Implementation | Classic Merge Sort
Asked in
Google 45 Microsoft 38 Amazon 42 Apple 30
34.0K Views
High Frequency
~25 min Avg. Time
890 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