Tutorialspoint
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].
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].
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)
ArrayseBayPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Check base case - if array has 1 or 0 elements, it's already sorted.
 Step 2: Find the middle point to divide the array into two halves.
 Step 3: Recursively call mergeSort on the left half of the array.
 Step 4: Recursively call mergeSort on the right half of the array.
 Step 5: Create a merge function to combine two sorted arrays.
 Step 6: Use two pointers to compare elements from both halves and merge in sorted order.
 Step 7: Handle remaining elements from either array after one is exhausted.

Submitted Code :