-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergeSort.js
67 lines (59 loc) · 1.29 KB
/
mergeSort.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const mergeSort = (list = [], rev = false) => {
if (list.length <= 1) {
return list;
}
let { leftHalf, rightHalf } = divide(list);
let left = mergeSort(leftHalf, rev);
let right = mergeSort(rightHalf, rev);
return sort(left, right, rev);
};
const divide = (list) => {
let mid = Math.floor(list.length / 2);
let leftHalf = list.slice(0, mid);
let rightHalf = list.slice(mid);
return { leftHalf, rightHalf };
};
const sort = (arg1, arg2, rev) => {
let newList = [];
let i = 0;
let j = 0;
if (rev) {
while (i < arg1.length && j < arg2.length) {
if (arg1[i] > arg2[j]) {
newList.push(arg1[i]);
i += 1;
} else {
newList.push(arg2[j]);
j += 1;
}
}
while (i < arg1.length) {
newList.push(arg1[i]);
i += 1;
}
while (j < arg2.length) {
newList.push(arg2[j]);
j += 1;
}
return newList;
} else {
while (i < arg1.length && j < arg2.length) {
if (arg1[i] < arg2[j]) {
newList.push(arg1[i]);
i += 1;
} else {
newList.push(arg2[j]);
j += 1;
}
}
while (i < arg1.length) {
newList.push(arg1[i]);
i += 1;
}
while (j < arg2.length) {
newList.push(arg2[j]);
j += 1;
}
return newList;
}
};