这次参考的是《高性能javascript》,因为看这本书的时候正好看到了这个排序的性能优化
思路比较简单,就是不断的分割,分到只剩一个数或者两个数为止,然后再合起来,举例,[5,3,9,6,10]
先分一半,[5,3,9]和[6,10],再把[5,3,9]分为[5,3]和[9],这时候[5,3]再分一次就可以合了,合成[3,5],[3,5]再和[9]合,一路合并回去
function merge(left, right) {
var result = [];
while (left.length > 0 && right.length > 0) {
if (left[0] < right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
}
return result.concat(left).concat(right);
}
function mergeSort(items) {
if (items.length == 1) {
return items;
}
var middle = Math.floor(items.length / 2),
left = items.slice(0, middle),
right = items.slice(middle);
return merge(mergeSort(left), mergeSort(right));
}
console.log(mergeSort([5,3,9,6,10,8]));
因为上面的写法在输入项比较多时会导致栈溢出,所以改成用循环,但是可读性比较差
function mergeSort(items) {
if (items.length == 1) {
return items;
}
var work = [];
for (var i = 0, len = items.length; i < len; i++) {
// 注意push的是数组,不是元素
work.push([items[i]]);
}
if(len % 2 !== 0)
work.push([]); //in case of odd number of items
for (var lim = len; lim > 1; lim = Math.floor((lim + 1) / 2)) {
for (var j = 0, k = 0; k < lim; j++ , k += 2) {
work[j] = merge(work[k], work[k + 1]);
}
if(len % 2 !== 0)
work[j] = []; //in case of odd number of items
}
return work[0];
}