ALGORITHMS_TODAY.COM
◄ BACK_TO_INDEX.exe
[SORTING] MODULE LOADED

MERGE_SORT

Divide and conquer. Split, sort recursively, merge. Guarantees optimal time at memory cost.

TIME_COMPLEXITY
O(n log n)
SPACE_COMPLEXITY
O(n)
DIFFICULTY
INTERMEDIATE
STABILITY
STABLE
PROCESS: MERGE_SORT.exe■ COMPLETE
> step[001/000]
██ COMPARE██ WRITE██ SORTED██ IDLE
[ range ] active recursion window · carets i / j / w #00e5ff (read/write heads) · mid #ffe600 (split point) · lower strip = AUX merge buffer
CLOCK_SPEED
DECRYPTED_SOURCE.js● LIVE
// MERGE_SORT.js — O(n log n) time complexity
function mergeSort(arr) {
  // Base case: 0 or 1 elements are already sorted
  if (arr.length <= 1) return arr;

  // Divide: split the array down the middle
  const mid = Math.floor(arr.length / 2);
  const left = mergeSort(arr.slice(0, mid));
  const right = mergeSort(arr.slice(mid));

  // Conquer: merge the two sorted halves
  return merge(left, right);
}

function merge(left, right) {
  const result = [];
  let i = 0, j = 0;

  // Repeatedly take the smaller of the two front values.
  // Using <= keeps equal elements in order — a stable sort.
  while (i < left.length && j < right.length) {
    if (left[i] <= right[j]) {
      result.push(left[i++]);
    } else {
      result.push(right[j++]);
    }
  }

  // Drain whatever remains in either half
  while (i < left.length) result.push(left[i++]);
  while (j < right.length) result.push(right[j++]);

  return result; // DECODED
}
DECRYPTED_LOGIC.txt
01Recursively split the array in half until pieces hold one element
02A single-element or empty sub-array is sorted by definition
03Merge two sorted halves by comparing their front elements
04Always take the smaller front value, preserving stable order
05Merges bubble back up the recursion into one sorted array