JS Built-ins
Algorithmsintermediate

Merge Sort

πŸ“– Usage Example
function mergeSort(arr) {
  if (arr.length <= 1) return arr;
  const mid = Math.floor(arr.length / 2);
  const left = mergeSort(arr.slice(0, mid));
  const right = mergeSort(arr.slice(mid));
  // merge left and right...
}

Merge sort divides the array recursively then merges sorted halves β€” O(n log n).

Merge Sort

Merge Sort is a divide-and-conquer algorithm that divides the array into halves, recursively sorts them, and then merges them back together.

Time Complexity: O(n log n) Space Complexity: O(n)

function mergeSort(arr: number[]): number[] {
  // Implement merge sort
  // Divide array, sort, and merge
}

mergeSort([64, 34, 25, 12, 22]) // [12, 22, 25, 34, 64]
πŸ’‘ Hints (4)
  • β€’ Use recursion to divide the array into halves.
  • β€’ Base case: array with 0 or 1 element is already sorted.
  • β€’ Implement a merge function that combines two sorted arrays.
  • β€’ Compare elements from both arrays and add the smaller one first.