Share This Tutorial

Views 18

How the Merge Sort Algorithm Works

Author Zak  |  Date 2024-10-15 17:35:48  |  Category Computer Science
Back Back

Merge Sort Algorithm Explained

Merge Sort is a highly efficient, stable sorting algorithm that follows the divide-and-conquer strategy. It works by recursively breaking down an unsorted list into smaller sublists until each sublist contains only one element (which is inherently sorted). Then, it repeatedly merges these sorted sublists to produce a final sorted list.

Steps involved in Merge Sort:

  1. Divide: The unsorted list is divided into two roughly equal halves.
  2. Conquer: Recursively sort the two sublists created in step 1.
  3. Combine: Merge the two sorted sublists into a single sorted list.

Example:

Let's consider the unsorted list: [8, 3, 1, 7, 0, 10, 2]

1. Divide:

2. Conquer:

3. Combine:

Implementation:

function mergeSort(arr) {
  if (arr.length <= 1) {
    return arr;
  }
  const mid = Math.floor(arr.length / 2);
  const leftArr = mergeSort(arr.slice(0, mid));
  const rightArr = mergeSort(arr.slice(mid));
  return merge(leftArr, rightArr);
}

function merge(leftArr, rightArr) {
  let resultArr = [];
  let leftIndex = 0;
  let rightIndex = 0;
  while (leftIndex < leftArr.length && rightIndex < rightArr.length) {
    if (leftArr[leftIndex] < rightArr[rightIndex]) {
      resultArr.push(leftArr[leftIndex]);
      leftIndex++;
    } else {
      resultArr.push(rightArr[rightIndex]);
      rightIndex++;
    }
  }
  // Add remaining elements from left or right array
  while (leftIndex < leftArr.length) {
    resultArr.push(leftArr[leftIndex]);
    leftIndex++;
  }
  while (rightIndex < rightArr.length) {
    resultArr.push(rightArr[rightIndex]);
    rightIndex++;
  }
  return resultArr;
}

Time and Space Complexity:

Advantages:

Disadvantages:

Conclusion:

Merge Sort is a highly efficient sorting algorithm that shines due to its consistent time complexity and stable nature. While it requires additional space, its overall performance makes it a valuable sorting tool for many applications.