DEV Community

0 seconds of 0 secondsVolume 90%
Press shift question mark to access a list of keyboard shortcuts
00:00
00:00
00:00
 
Chris
Chris

Posted on

Merge Sort

Currently going over some algorithms and wanted to create a short walkthrough video.

Here is the code used in this video.

function merge(arr1, arr2) {
  let results = [];
  let idx1 = 0;
  let idx2 = 0;
  while (idx1 < arr1.length && idx2 < arr2.length) {
    if (arr1[idx1] < arr2[idx2]) {
      results.push(arr1[idx1]);
      idx1++;
    } else {
      results.push(arr2[idx2]);
      idx2++;
    }
  }
  while (idx1 < arr1.length) {
    results.push(arr1[idx1]);
    idx1++;
  }
  while (idx2 < arr2.length) {
    results.push(arr2[idx2]);
    idx2++;
  }
  return results;
}

function mergeSort(arr) {
  if (arr.length <= 1) return arr;
  let mid = Math.floor(arr.length / 2);
  let left = mergeSort(arr.slice(0, mid));
  let right = mergeSort(arr.slice(mid));
  return merge(left, right);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Image of Checkly

Incident Management 101: What Devs Need to Know in 2025

  • Detect issues before your users do
  • Use synthetic checks for proactive coverage
  • Automate root cause workflows
  • Communicate incidents clearly to your team
  • Learn how to triage, escalate, and resolve faster

Watch session

👋 Kindness is contagious

Please consider leaving a ❤️ or a friendly comment if you found this post helpful!

Okay