Data Structure and Algorithm
Algorithms
Sorting
Merge Sort

Merge Sort in JavaScript - Complete Guide

Introduction

Merge Sort is a Divide and Conquer algorithm. It divides the input array in two halves, calls itself for the two halves, and then merges the two sorted halves.

The merge() function is used for merging two halves. The merge(arr, l, m, r) is a key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one in a sorted manner. See the following implementation for details.

Merge Sort Algorithm

The recursive approach of merge sort can be outlined as follows:

MergeSort(arr[], l, r)
If r > l
    1. Find the middle point to divide the array into two halves:
            middle m = (l + r) / 2
    2. Call mergeSort for first half:
            Call mergeSort(arr, l, m)
    3. Call mergeSort for second half:
            Call mergeSort(arr, m + 1, r)
    4. Merge the two halves sorted in step 2 and 3:
            Call merge(arr, l, m, r)

How Merge Sort Works?

Consider an example array {38, 27, 43, 3, 9, 82, 10}.

If we take a closer look at the process, we can see that the array is recursively divided in two halves till the size becomes 1. Once the size becomes 1, the merge process comes into action and starts merging arrays back till the complete array is merged.

Visualization of Divide and Conquer

Merge two Sorted Arrays

Given two sorted arrays, the task is to merge them in a sorted manner.

Examples:

  • Input: arr1[] = {1, 3, 4, 5}, arr2[] = {2, 4, 6, 8} Output: arr3[] = {1, 2, 3, 4, 4, 5, 6, 8}
  • Input: arr1[] = {5, 8, 9}, arr2[] = {4, 7, 8} Output: arr3[] = {4, 5, 7, 8, 8, 9}

Method 1: (O(n1 * n2) Time and O(n1+n2) Extra Space)

  1. Create an array arr3[] of size n1 + n2.
  2. Copy all n1 elements of arr1[] to arr3[].
  3. Traverse arr2[] and one by one insert elements (like insertion sort) of arr2[] to arr3[]. This step takes O(n1 * n2) time.

Method 2: (O(n1 + n2) Time and O(n1 + n2) Extra Space)

The idea is to use Merge function of Merge sort.

  1. Create an array arr3[] of size n1 + n2.
  2. Simultaneously traverse arr1[] and arr2[].
    • Pick smaller of current elements in arr1[] and arr2[], copy this smaller element to next position in arr3[] and move ahead in arr3[] and the array whose element is picked.
  3. If there are remaining elements in arr1[] or arr2[], copy them also in arr3[].

Dry Run Example:

  • Initially: arr1 = [5, 8, 9], arr2 = [4, 7, 8], arr3 = []
  • Step 1: arr3 = [4] (4 from arr2)
  • Step 2: arr3 = [4, 5] (5 from arr1)
  • Step 3: arr3 = [4, 5, 7] (7 from arr2)
  • Step 4: arr3 = [4, 5, 7, 8] (8 from arr2, first while loop breaks)
  • Step 5: arr3 = [4, 5, 7, 8, 8] (Second while loop copies remaining from arr1)
  • Step 6: arr3 = [4, 5, 7, 8, 8, 9] (Merged Sorted Array)

Implementation:

function merge(a, b, m, n) {
    let c = [];
    let i = 0, j = 0, k = 0;
    
    while(i < m && j < n) {
        if(a[i] < b[j]) {
            c[k] = a[i];
            k++; i++;
        } else {
            c[k] = b[j];
            k++; j++;
        }
    }
    
    while(i < m) {
        c[k] = a[i];
        k++; i++;
    }
    
    while(j < n) {
        c[k] = b[j];
        k++; j++;
    }
    return c;
}
 
let a = [5, 8, 9];
let b = [4, 7, 8];
let output = merge(a, b, a.length, b.length);
console.log(output); // [4, 5, 7, 8, 8, 9]

Complete Merge Sort Implementation

Using the efficient merging logic, we can construct the full recursive Merge Sort algorithm:

function merge(arr, l, m, r) {
    let n1 = m - l + 1;
    let n2 = r - m;
 
    let L = new Array(n1);
    let R = new Array(n2);
 
    for (let i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (let j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];
 
    let i = 0;
    let j = 0;
    let k = l;
 
    while (i < n1 && j < n2) {
        if (L[i] <= R[j]) {
            arr[k] = L[i];
            i++;
        } else {
            arr[k] = R[j];
            j++;
        }
        k++;
    }
 
    while (i < n1) {
        arr[k] = L[i];
        i++;
        k++;
    }
 
    while (j < n2) {
        arr[k] = R[j];
        j++;
        k++;
    }
}
 
function mergeSort(arr, l, r) {
    if (l >= r) {
        return; 
    }
    let m = l + parseInt((r - l) / 2);
    
    mergeSort(arr, l, m);
    mergeSort(arr, m + 1, r);
    merge(arr, l, m, r);
}
 
let arr = [38, 27, 43, 3, 9, 82, 10];
let arr_size = arr.length;
 
mergeSort(arr, 0, arr_size - 1);
console.log("Sorted array is:", arr);

Analysis of Merge Sort

A merge sort consists of several passes over the input. The first pass merges segments of size 1, the second merges segments of size 2, and the i-th pass merges segments of size 2^(i-1). Thus, the total number of passes is [logâ‚‚n]. As merge showed, we can merge two sorted segments in linear time, which means that each pass takes O(n) time. Since there are [logâ‚‚n] passes, the total computing time is O(n log n).

Applications of Merge Sort:

  • Merge Sort is useful for sorting linked lists in O(N log N) time. In the case of linked lists, the case is different mainly due to the difference in memory allocation of arrays and linked lists. Unlike arrays, linked list nodes may not be adjacent in memory. Unlike an array, in the linked list, we can insert items in the middle in O(1) extra space and O(1) time. Therefore, the merge operation of merge sort can be implemented without extra space for linked lists. In arrays, we can do random access as elements are contiguous in memory. Let us say we have an integer (4-byte) array A and let the address of A[0] be x then to access A[i], we can directly access the memory at (x + i*4). Unlike arrays, we can not do random access in the linked list. Quick Sort requires a lot of this kind of access. In a linked list to access i'th index, we have to travel each and every node from the head to i'th node as we don't have a contiguous block of memory. Therefore, the overhead increases for quicksort. Merge sort accesses data sequentially and the need of random access is low.
  • Inversion Count Problem
  • Used in External Sorting

Advantages of Merge Sort:

  • Merge sort has a time complexity of O(n log n), which means it is relatively efficient for sorting large datasets.
  • Merge sort is a stable sort, which means that the order of elements with equal values is preserved during the sort.
  • It is easy to implement thus making it a good choice for many applications.
  • It is useful for external sorting. This is because merge sort can handle large datasets, it is often used for external sorting, where the data being sorted does not fit in memory.
  • The merge sort algorithm can be easily parallelized, which means it can take advantage of multiple processors or cores to sort the data more quickly.
  • Merge sort requires relatively few additional resources (such as memory) to perform the sort. This makes it a good choice for systems with limited resources.

Drawbacks of Merge Sort:

  • Slower compared to the other sort algorithms for smaller tasks. Although efficient for large datasets its not the best choice for small datasets.
  • The merge sort algorithm requires an additional memory space of O(n) for the temporary array. This is to store the subarrays that are used during the sorting process.
  • It goes through the whole process even if the array is sorted.
  • It requires more code to implement since we are dividing the array into smaller subarrays and then merging the sorted subarrays back together.

Solution of the drawback for additional storage:

Use linked list.