Skip to content

Instantly share code, notes, and snippets.

@aggieben
Created March 7, 2013 22:10
Show Gist options
  • Select an option

  • Save aggieben/5112294 to your computer and use it in GitHub Desktop.

Select an option

Save aggieben/5112294 to your computer and use it in GitHub Desktop.
/*
A = array(1, 3, 5, null, null, null);
B = array(2, 4, 6);
merge_sort(A, B);
console.log(B)
>> (1,2,3,4,5,6)
*/
/* left array is big enough for results, scan both arrays and leave result sorted, empty elements are null */
function merge_sort(A, B) {
var i = A.length - 1;
var j = B.length - 1;
var pos = A.length - 1;
while (i > 0 || j > 0) {
if (A[i] != null) {
if (j < 0 || A[i] >= B[j]) {
A[pos] = A[i];
i--;
} else if (i < 0 || B[j] > A[i]) {
A[pos] = B[j];
j--;
}
pos--;
} else {
i--;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment