Merge Sort Algorithm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function mergeSort(arr) {
if (arr.length === 1) {
return arr;
}
const center = Math.floor(arr.length / 2);
const left = arr.slice(0, center);
const right = arr.slice(center);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right) {
const results = [];
while (left.length && right.length) {
if (left[0] < right[0]) {
results.push(left.shift());
} else {
results.push(right.shift());
}
}
return [ ...results, ...left, ...right ];
}