Skip to content

Instantly share code, notes, and snippets.

@thm-design
Created March 28, 2016 15:55
Show Gist options
  • Save thm-design/32e60d8fc0070e8563ad to your computer and use it in GitHub Desktop.
Save thm-design/32e60d8fc0070e8563ad to your computer and use it in GitHub Desktop.
Merge Sort Algorithm
/*
Merge Sort
*/
const mergeSort = (nums) => {
if (nums.length < 2) return nums;
const length = nums.length;
const middle = Math.floor(length / 2);
const left = nums.slice(0, middle);
const right = nums.slice(middle, length);
return merge(mergeSort(left), mergeSort(right));
};
const merge = (left, right) => {
const results = [];
while (left.length && right.length) {
if (left[0] <= right[0]) results.push(left.shift());
else results.push(right.shift());
}
while(left.length) results.push(left.shift());
while(right.length) results.push(right.shift());
return results;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment