-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmergeSort.js
More file actions
38 lines (35 loc) · 945 Bytes
/
mergeSort.js
File metadata and controls
38 lines (35 loc) · 945 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
30
31
32
33
34
35
36
37
38
/*
* 归并排序,具体分析可以参考https://github.com/front-thinking/blogs/issues/2
*/
function mergeSort(arr) {
var n = arr.length, index = Math.floor(n/2), leftArr, rightArr;
if (arr.length === 0 || arr.length === 1) {
return arr;
}
leftArr = mergeSort(arr.slice(0, index));
rightArr = mergeSort(arr.slice(index, n));
return merge(leftArr, rightArr);
}
/*
* 合并过程
*/
function merge (arrLeft, arrRight) {
var k = i = j = 0, ll = arrLeft.length, lr = arrRight.length, nl = ll + lr, res = [];
while (i < ll && j < lr) {
if (arrLeft[i] > arrRight[j]){
res[k++] = arrRight[j++];
} else {
res[k++] = arrLeft[i++];
}
}
if (i >= ll) {
while (k < nl) {
res[k++] = arrRight[j++];
}
} else if (j >= lr) {
while (k < nl) {
res[k++] = arrLeft[i++];
}
}
return res;
}