Skip to content

Instantly share code, notes, and snippets.

@lh0x00
Created March 30, 2019 07:48
Show Gist options
  • Save lh0x00/d2f740f79a918ec05da3bedec362acdf to your computer and use it in GitHub Desktop.
Save lh0x00/d2f740f79a918ec05da3bedec362acdf to your computer and use it in GitHub Desktop.
function merge(left, right) {
let arr = [], leftIndex = 0, rightIndex = 0;
while(left.length > leftIndex && right.length > rightIndex) {
if (left[leftIndex] < right[rightIndex]) {
arr.push(left[leftIndex]);
leftIndex++;
} else {
arr.push(right[rightIndex]);
rightIndex++;
}
}
return arr.concat(
left.slice(leftIndex).concat(
right.slice(rightIndex)
)
);
}
function sort(arr) {
if (arr.length <= 1) {
return arr;
}
const middle = Math.floor(arr.length / 2);
const left = arr.slice(0, middle);
const right = arr.slice(middle, arr.length);
return merge(sort(left), sort(right));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment