Skip to content

Instantly share code, notes, and snippets.

@willjw3
Created February 22, 2019 14:40
Show Gist options
  • Save willjw3/0dad603ce8108c39c7163dcd8d1c5af3 to your computer and use it in GitHub Desktop.
Save willjw3/0dad603ce8108c39c7163dcd8d1c5af3 to your computer and use it in GitHub Desktop.
function mergeSort(array) {
if (array.length > 1) {
let mid = Math.floor(array.length / 2);
let lhs = mergeSort(array.slice(0, mid));
let rhs = mergeSort(array.slice(mid));
return merge(lhs, rhs);
} else {
return array;
}
}
function merge(left, right) {
let i = 0;
let j = 0;
let sortedArr = [];
while (i < left.length && j < right.length) {
if (left[i] < right[j]) {
sortedArr.push(left[i]);
i++;
} else {
sortedArr.push(right[j]);
j++;
}
}
while (i < left.length) {
sortedArr.push(left[i]);
i++;
}
while (j < right.length) {
sortedArr.push(right[j]);
j++;
}
return sortedArr;
}
let myArray = [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
console.log(mergeSort(myArray));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment