1 function merge(left, right) {
2 var result = [];
3
4 while (left.length > 0 && right.length > 0) {
5 if (left[0] < right[0]) {
6 result.push(left.shift());
7 } else {
8 result.push(right.shift());
9 }
10 }
11 return result.concat(left).concat(right);
12 }
13
14 function mergeSort(items) {
15 if (items.length == 1) {
16 return items;
17 }
18
19 var work = [];
20 for (var i = 0, len = items.length; i < len; i++) {
21 work.push([items[i]]);
22 }
23 work.push([]); //如果数组长度为奇数
24 for (var lim = len; lim > 1; lim = (lim + 1) / 2) {
25 for (var j = 0, k = 0; k < lim; j++, k += 2) {
26 work[j] = merge(work[k], work[k + 1]);
27 }
28 work[j] = []; //如果数组长度为奇数
29 }
30 return work[0];
31 }