Home >Web Front-end >JS Tutorial >Example codes for 3 types of merge operations in js_javascript skills

Example codes for 3 types of merge operations in js_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:18:09885browse

第一种:

复制代码 代码如下:

/**Brother Liang's*/
function merge(a, b) {
    var aLen = a.length,
        bLen = b.length,
        maxLen = Math.max(aLen, bLen),
        sumLen = aLen bLen,
        result = [],
        ap = 0,
        bp = 0;

     while (result.length < sumLen) {
        if (ap < aLen && bp < bLen) {
            if(a[ap] > b[bp]){
                result.push(b[bp ]);
            } else {
                result.push(a[ap ]);
            }
        } else if (!(ap < aLen)){
            while(bp < bLen){
                result.push(b[bp ]);
            }
        } else if (!(bp < bLen)){
            while(ap < aLen){
                result.push(a[ap ]);
            }
        }
    }
    return result;
}

第二种:

复制代码 代码如下:

/**Lu Jun*/
function merge(arr1, arr2){

    var i = 0;
    var j = 0;
    var c = 0;
    var k;
    var len1 = arr1.length;
    var len2 = arr2.length;
    var arr = [];
    for(;i        if( arr1[i] > arr2[j]  ){
            arr.push( arr2[j] );
            j ;
        }else{
            arr.push( arr1[i] );
            i ;
        }
        //if(i==len1 || j==len2){
        //    break;
        //}
    }

    if(i==len1){
        //arr = arr.concat(arr2.slice(j));

        for(k=j; k            arr.push( arr2[k] );
        }
    }

    if(j==len2){
        //arr = arr.concat(arr1.slice(i))
        for(k=i; k            arr.push( arr1[k] );
        }

    }

    return arr;
}

第三种:

复制代码 代码如下:

/*金锐的*/
function merge(a,b){
    var x = 0;
    var l = 0;
    var list = [];
    var aLen = a.length;
    var bLen = b.length;

    for(var i = 0; i < bLen; i ){
        for(var j = x; j < aLen; j ){
            if(b[i] < a[j]){
                list.push(b[i]);
                l = i;
                break;
            }else{               
                list.push(a[j]);
                x ;
            }
        }    
    }           

    if(x == a.length){
        for(var y = l; y < bLen; y ){
            list.push(b[y]);
        }
    }else{
        for(var z = x; z < aLen; z ){
            list.push(a[z]);
        }
    }

    return list;
}

经过测试2个有序20W长度的数组归并耗时都在15毫秒以下。

以下有几条经验(在大量操作的时候才能体现,平时不需要做这样的优化。代码可读性还是第一原则)

1:数组的concat方法比直接for循环push要慢。

2:for循环比while循环快。

3:var a = b || 3; //这种操作很消耗时间

4: break,continue 在已确定不需要再循环时很耗时。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn