
Problem
Solution
Submissions
Merge Sort
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to implement the Merge Sort algorithm to sort an array of integers in ascending order. Merge Sort is a divide-and-conquer algorithm that divides the array into two halves, sorts them separately, and then merges the sorted halves back together.
Example 1
- Input: arr = [38, 27, 43, 3, 9, 82, 10]
- Output: [3, 9, 10, 27, 38, 43, 82]
- Explanation:
- The initial array is [38, 27, 43, 3, 9, 82, 10].
- Divide array into two halves: [38, 27, 43] and [3, 9, 82, 10].
- Continue dividing until single elements: [38], [27], [43], [3], [9], [82], [10].
- Merge pairs back together in sorted order: [27, 38], [43], [3, 9], [10, 82].
- Continue merging until final sorted array: [3, 9, 10, 27, 38, 43, 82].
- The initial array is [38, 27, 43, 3, 9, 82, 10].
Example 2
- Input: arr = [12, 11, 13, 5, 6, 7]
- Output: [5, 6, 7, 11, 12, 13]
- Explanation:
- The initial array is [12, 11, 13, 5, 6, 7].
- Divide into [12, 11, 13] and [5, 6, 7].
- Further divide into [12], [11, 13] and [5], [6, 7].
- Merge sorted pairs: [11, 12, 13] and [5, 6, 7].
- Final merge produces [5, 6, 7, 11, 12, 13].
- The initial array is [12, 11, 13, 5, 6, 7].
Constraints
- 1 ≤ arr.length ≤ 1000
- -1000 ≤ arr[i] ≤ 1000
- The array may contain duplicate elements
- Time Complexity: O(n log n)
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Divide the array into two halves recursively until single elements remain
- Create a merge function to combine two sorted arrays
- Use two pointers to compare elements from both halves during merging
- Handle remaining elements when one half is exhausted
- Use temporary arrays to store the divided subarrays
- Apply divide-and-conquer principle consistently