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:
- Dividing the array into two halves recursively until single elements remain
- Merging the divided arrays back together in sorted order
- 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code