DEV Community

0 seconds of 7 minutes, 49 secondsVolume 90%
Press shift question mark to access a list of keyboard shortcuts
00:00
00:00
07:49
 
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 Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more