Js 3 kinds of merge operation instance code
- 2020-03-26 21:40:35
- OfStack
The first:
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;
}
The second:
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<len1 && j<len2;){
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<len2; k++){
arr.push( arr2[k] );
}
}
if(j==len2){
//arr = arr.concat(arr1.slice(i))
for(k=i; k<len1; k++){
arr.push( arr1[k] );
}
}
return arr;
}
The third:
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;
}
After testing, the merge time of two ordered 20W arrays is less than 15 milliseconds.
The following are a few lessons (in a large number of operations to reflect, usually do not need to do this optimization. Code readability or first rule)
1: the concat method of arrays is slower than the direct for loop push.
2: for loop is faster than while loop.
3: var a = b| | 3; // this kind of operation takes a lot of time
4: break,continue is time consuming when it is determined that recirculation is not required.