How to implement merge sort in JavaScript?

The Merge Sort algorithm is a divide-and-conquer sorting technique that recursively divides an array into smaller subarrays until each contains a single element, then merges them back in sorted order.

The algorithm works by continuously splitting the array in half until it cannot be divided further. Once we have individual elements, we merge them back together in a sorted manner, comparing elements from each subarray and placing them in the correct order.

Input-output Scenario

Consider an unsorted array that we want to sort using merge sort:

Input = [12, 34, 11, 1, 54, 25, 67, 45]
Output = [1, 11, 12, 25, 34, 45, 54, 67]

The elements are sorted in ascending order through the divide-and-conquer approach.

How Merge Sort Works

Let's trace through merge sort with array: [30, 20, 40, 0, 10, 80, 11]

Step 1: Check if left index is less than right index, then calculate the midpoint to divide the array.

Step 2: Divide the 7-element array into two parts: 4 elements on the left, 3 on the right.

Step 3: Continue dividing each subarray until we have individual elements.

Step 4: Compare and merge elements back together in sorted order, starting with the smallest subarrays.

Step 5: Continue merging until we have the final sorted array.

Algorithm Steps

  • Declare array, left index, right index, and middle variable

  • Check if left index > right index, then return

  • Calculate mid = (left index + right index) / 2

  • Recursively call mergesort on first half: mergesort(array, left, mid)

  • Recursively call mergesort on second half: mergesort(array, mid+1, right)

  • Merge the sorted halves: merge(array, left, mid, right)

Implementation

Here's a complete implementation of merge sort in JavaScript:

<!DOCTYPE html>
<html>
<head>
   <title>Merge Sort</title>
</head>
<body>
   <script>
      function merge_Arrays(left_sub_array, right_sub_array) {
         let array = []
         while (left_sub_array.length && right_sub_array.length) {
            if (left_sub_array[0] < right_sub_array[0]) {
               array.push(left_sub_array.shift())
            } else {
               array.push(right_sub_array.shift())
            }
         }
         return [...array, ...left_sub_array, ...right_sub_array]
      }
      
      function merge_sort(unsorted_Array) {
         const middle_index = Math.floor(unsorted_Array.length / 2)
         if(unsorted_Array.length < 2) {
            return unsorted_Array
         }
         const left_sub_array = unsorted_Array.slice(0, middle_index)
         const right_sub_array = unsorted_Array.slice(middle_index)
         return merge_Arrays(merge_sort(left_sub_array), merge_sort(right_sub_array))
      }
      
      let unsorted_Array = [39, 28, 44, 4, 10, 83, 11];
      let sorted_Array = merge_sort([...unsorted_Array]); // Create copy to preserve original
      
      document.write("Original array: " + unsorted_Array + "<br>");
      document.write("Sorted array: " + sorted_Array);
   </script>
</body>
</html>
Original array: 39,28,44,4,10,83,11
Sorted array: 4,10,11,28,39,44,83

Time and Space Complexity

  • Time Complexity: O(n log n) in all cases (best, average, worst)

  • Space Complexity: O(n) for the temporary arrays used during merging

  • Stability: Merge sort is stable - maintains relative order of equal elements

Key Points

  • Merge sort guarantees O(n log n) performance regardless of input data

  • It requires additional memory space for temporary arrays

  • The algorithm works well for large datasets and external sorting

  • It's stable and predictable but not in-place

Conclusion

Merge sort is a reliable divide-and-conquer algorithm that provides consistent O(n log n) performance. While it requires extra memory space, its stability and predictable behavior make it suitable for applications where consistent performance is more important than memory efficiency.

Updated on: 2026-03-15T23:18:59+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements