First type:
Copy Code code as follows:
/** '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++]);
}
Or else if (! AP < ALen)) {
while (BP < Blen) {
Result.push (b[bp++]);
}
Or else if (! bp < Blen)) {
while (AP < ALen) {
Result.push (a[ap++]);
}
}
}
return result;
}
The second type:
Copy Code code as follows:
/** Ru 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<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 type:
Copy Code code as follows:
* * Jinrui's/
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 2 sequential 20W-length array merges, it takes less than 15 milliseconds to merge.
Here are a few of the experience (in a large number of operations to reflect, usually do not need to do this optimization.) Code readability or the first principle)
1: The concat method of the array is slower than the direct for loop push.
The 2:for loop is faster than the while loop.
3:var A = B | | 3; This is a time-consuming operation.
4:break,continue is time-consuming when it is determined that there is no need to recycle.