Last active
August 29, 2015 14:25
-
-
Save laverdet/a41adde4072d12d42312 to your computer and use it in GitHub Desktop.
How to merge sorted arrays
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
function mergeSorted(a, b) { | |
var array = new Array(a.length + b.length); | |
var ii = a.length + b.length - 1; | |
var jj = a.length - 1, kk = b.length - 1; | |
while (jj >= 0 || kk >= 0) { | |
array[ii--] = (jj < 0 || a[jj] < b[kk]) ? b[kk--] : a[jj--]; | |
} | |
return array; | |
} | |
var a = [1, 3, 7, 9, 11]; | |
var b = [2, 3, 4, 5, 12, 13]; | |
console.log(mergeSorted(a, b)); | |
// [ 1, 2, 3, 3, 4, 5, 7, 9, 11, 12, 13 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment