Last active
August 29, 2015 14:04
-
-
Save DevinXian/2f87e75117501ec1308b to your computer and use it in GitHub Desktop.
MergeSort in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 合并排序--升序 | |
* 算法效率: O(arrA.length + arrB.length) | |
* 条件为:arrA和arrB均是升序排列数组 | |
* @Returns 合并后数组 | |
*/ | |
function merge_asc(arrA, arrB) { | |
if (!arrA instanceof Array || !arrB instanceof Array) { | |
console.log('invalid array'); | |
return; | |
} | |
var arrC = new Array(arrA.length + arrB.length); | |
var i = 0, j = 0, k = 0; | |
while (i < arrA.length && j < arrB.length) { | |
if (arrA[i] <= arrB[j]) { | |
arrC[k] = arrA[i]; | |
++i; | |
++k; | |
} else { | |
arrC[k] = arrB[j]; | |
++j; | |
++k; | |
} | |
} | |
while (i < arrA.length) { | |
arrC[k] = arrA[i]; | |
++i; | |
++k; | |
} | |
while (j < arrB.length) { | |
arrC[k] = arrB[j]; | |
++j; | |
++k; | |
} | |
return arrC; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
结果不正确