forked from sl1673495/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
归并排序.js
39 lines (34 loc) · 706 Bytes
/
归并排序.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
function mergeSort(arr) {
let l = arr.length;
if (l === 1) return arr;
let m = Math.round(l / 2);
let left = arr.slice(0, m);
let right = arr.slice(m);
return merge(mergeSort(left), mergeSort(right));
}
function merge(arr1, arr2) {
let l1 = arr1.length;
let l2 = arr2.length;
let i1 = 0;
let i2 = 0;
let r = [];
while (i1 < l1 && i2 < l2) {
let item1 = arr1[i1];
let item2 = arr2[i2];
if (item1 < item2) {
r.push(item1);
i1++;
} else {
r.push(item2);
i2++;
}
}
while (i1 < l1) {
r.push(arr1[i1++]);
}
while (i2 < l2) {
r.push(arr2[i2++]);
}
return r;
}
console.log(mergeSort([1, 4, 2, 3, 5, 2, 7, 3, 17, 25, 19]))