-
Notifications
You must be signed in to change notification settings - Fork 211
Expand file tree
/
Copy pathmergeSort.js
More file actions
29 lines (26 loc) · 774 Bytes
/
Copy pathmergeSort.js
File metadata and controls
29 lines (26 loc) · 774 Bytes
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
const list = [5, 4, -3, 2, 1]
const mergeSort = (list) => {
if (list.length <= 1) return list;
const middle = list.length / 2;
const left = list.slice(0, middle);
const right = list.slice(middle, list.length);
return merge(mergeSort(left), mergeSort(right));
}
const merge = (left, right) => {
var result = [];
while (left.length || right.length) {
if (left.length && right.length) {
if (left[0] < right[0]) {
result.push(left.shift())
} else {
result.push(right.shift())
}
} else if (left.length) {
result.push(left.shift())
} else {
result.push(right.shift())
}
}
return result;
}
console.log(mergeSort(list))