《高性能javascript》 --- in case of odd number of items(奇怪的条目的数量)

不知道是做着故意放的还是什么原因。总之运行后就会出现问题(奇怪的条目的数量)

 

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 work = [];
for (var i=0, len=items.length; i < len; i++){
work.push([items[i]]);
}
work.push([]); //in case of odd number of items
for (var lim=len; lim > 1; lim = (lim+1)/2){
for (var j=0,k=0; k < lim; j++, k+=2){
work[j] = merge(work[k], work[k+1]);
}
work[j] = []; //in case of odd number of items
}
return work[0];
}

问题出在标红的这3块

 

附上正确代码:

 

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 work = [];
    for (var i=0, len=items.length; i < len; i++){
        work.push([items[i]]);
    }
    // work.push([]); //in case of odd number of items
    for (var lim=len; lim > 1; lim = lim/2){
        for (var j=0,k=0; k < lim; j++, k+=2){
            work[j] = merge(work[k], work[k+1]);
        }
        // work[j] = []; //in case of odd number of items
    }
    return work[0];
}

 

posted @ 2016-11-30 17:09  四两websir  阅读(371)  评论(0编辑  收藏  举报