-
Notifications
You must be signed in to change notification settings - Fork 0
/
foo.js
44 lines (35 loc) · 863 Bytes
/
foo.js
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
function mergeSort(arr) {
if (arr.length <= 1) return arr;
let midIdx = Math.floor(arr.length / 2);
let left = mergeSort(arr.slice(0, midIdx));
let right = mergeSort(arr.slice(midIdx, arr.length));
return merge(left, right);
}
function merge(left, right) {
result = [];
let i = 0;
let j = 0;
while (left[i] != undefined && right[j] != undefined) {
if (left[i] < right[j]) {
result.push(left[i]);
i++;
} else {
result.push(right[j]);
j++;
}
}
while (left[i] != undefined) {
result.push(left[i]);
i++;
}
while (right[j] != undefined) {
result.push(right[j]);
j++;
}
return result;
}
console.log(merge([1, 2], [3, 4]));
console.log(merge([1, 2, 4], [3, 4, 8]));
console.log(mergeSort([1, 2, 3, 4, 0]));
console.log(mergeSort([1, 2, 4, 5, 5, 9]));
console.log(mergeSort([]));