三个有序数据 var a=[2,3,4,5,6,9,10], b=[6,9,10,11,13,15], c=[2,3,4,7,9,10]; 存储合并后的数组

//三个有序数据
var a=[2,3,4,5,6,9,10], b=[6,9,10,11,13,15], c=[2,3,4,7,9,10];
//存储合并后的数组
var d=[],len = 0;
 
//第一步
for(var i=0,j=0,k=0;i<a.length && j<b.length && k<c.length;){
    var aValue = a[i];
    var bValue = b[j];
    var cValue = c[k];
    if(aValue <= bValue && aValue <= cValue){
        d[len++] = aValue;
        i++;
    }else if(bValue <= cValue && bValue <= cValue){
        d[len++] = bValue;
        j++;
    }else if(cValue <= aValue && cValue <= bValue){
        d[len++] = cValue;
        k++;
    }
}
 
console.log(d);
 
//第二步
if(i == a.length){
    for(;j<b.length && k<c.length;){
        var bValue = b[j];
        var cValue = c[k];
        if(bValue <= cValue){
            d[len++] = bValue;
            j++;
        }else{
            d[len++] = cValue;
            k++;
        }
    }
}else if(j == b.length){
    for(;i<a.length && k<c.length;){
        var aValue = a[i];
        var cValue = c[k];
        if(aValue <= cValue){
            d[len++] = aValue;
            i++;
        }else{
            d[len++] = cValue;
            k++;
        }
    }
}else if(l == c.length){
    for(;i<a.length && j<b.length;){
        var aValue = a[i];
        var bValue = b[j];
        if(aValue <= cValue){
            d[len++] = aValue;
            i++;
        }else{
            d[len++] = bValue;
            j++;
        }
    }
}
 
console.log(d);
 
//第三步
if(i<a.length){
    for(;i<a.length;i++){
        d[len++] = a[i];
    }
}else if(j<b.length){
    for(;j<b.length;j++){
        d[len++] = b[j];
    }
}else if(k<c.length){
    for(;k<c.length;k++){
        d[len++] = c[k];
    }
}
 
console.log(d);
Last modification:September 9th, 2019 at 02:41 pm
如果觉得我的文章对你有用,请随意赞赏

Leave a Comment