Last active
December 2, 2021 07:27
-
-
Save iexa/fad8f21768283fa831e43b6b4cacc5c0 to your computer and use it in GitHub Desktop.
merge sorted arrays js
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
// const {log} = console | |
// merge sorted | |
a = [0, 4, 6, 7]; | |
b = [1, 2, 3, 4, 8]; | |
function mergeSorted(x1, x2) { | |
const out = []; | |
const [l1, l2] = [x1.length, x2.length]; | |
let [i1, i2] = [0, 0]; | |
for(let i=0; i < l1+l2; i++) { | |
if(i1 < l1 && i2 < l2) | |
if(x1[i1] < x2[i2]) | |
out.push(x1[i1++]) | |
else | |
out.push(x2[i2++]) | |
else if(i1 < l1) | |
out.push(x1[i1++]) | |
else | |
out.push(x2[i2++]) | |
} | |
return out | |
} | |
mergeSorted(a, b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment