Skip to content

Instantly share code, notes, and snippets.

@srph
Created December 27, 2019 00:42
Show Gist options
  • Save srph/e39234a3c77b69c3c3faa2639c4089ae to your computer and use it in GitHub Desktop.
Save srph/e39234a3c77b69c3c3faa2639c4089ae to your computer and use it in GitHub Desktop.
JS: Merge sort - programming exercise
const array = [38, 27, 24, 56, 12, 32, 16, 11, 15, 25, 29];
console.log(mergeSort(array));
function mergeSort(array) {
if (array.length <= 1) {
return array;
}
const middle = Math.floor(array.length / 2);
const left = array.slice(0, middle);
const right = array.slice(middle);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right) {
const result = [];
let lindex = 0;
let rindex = 0;
while (lindex < left.length && rindex < right.length) {
if (left[lindex] < right[rindex]) {
result.push(left[lindex]);
lindex++;
} else {
result.push(right[rindex]);
rindex++;
}
}
return [...result, ...left.slice(lindex), ...right.slice(rindex)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment