Skip to content

Instantly share code, notes, and snippets.

@dev-sampsonorson
Created February 12, 2022 19:50
Show Gist options
  • Save dev-sampsonorson/ffabc4497b38c25bc31afbc109748754 to your computer and use it in GitHub Desktop.
Save dev-sampsonorson/ffabc4497b38c25bc31afbc109748754 to your computer and use it in GitHub Desktop.
Recursive implementation of merge sort
const input1 = [-5, 20, 10, 3, 2, 0];
const merge = (data, start, min, end) => {
const temp = [];
let i = start, j = min + 1, x = 0;
while (i <= min && j <= end) {
if (data[i] > data[j]) {
temp.push(data[j++]);
}
if (data[i] <= data[j]) {
temp.push(data[i++]);
}
}
while (i <= min)
temp.push(data[i++]);
while (j <= end)
temp.push(data[j++]);
for (i = start; i <= end; i++)
data[i] = temp.splice(0, 1)[0];
};
const mergeSort = (data, start, end) => {
if (start < end) {
const mid = Math.floor((start + end) / 2);
mergeSort(data, start, mid);
mergeSort(data, mid + 1, end);
merge(data, start, mid, end);
}
return data;
};
console.log(mergeSort(input1, 0, input1.length - 1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment