Skip to content

Instantly share code, notes, and snippets.

@jack-wong-build
Created December 31, 2013 18:58
Show Gist options
  • Save jack-wong-build/8200874 to your computer and use it in GitHub Desktop.
Save jack-wong-build/8200874 to your computer and use it in GitHub Desktop.
Given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order.
var mergeTwoSortedArray = function(array1, array2){
var array1IndexEnd = array1.length - array2.length - 1;
var arrayExtraIndexEnd = array1.length - 1;
var array2IndexEnd = array2.length - 1;
while( array2IndexEnd >= 0){
if ( array1[array1IndexEnd] > array2[array2IndexEnd]){
array1[arrayExtraIndexEnd] = array1[array1IndexEnd];
arrayExtraIndexEnd--;
array1IndexEnd--
} else {
array1[arrayExtraIndexEnd] = array2[array2IndexEnd];
arrayExtraIndexEnd--;
array2IndexEnd--;
}
}
return array1;
}
// var result = mergeTwoSortedArray([2, 4, 5, 26, 92, '', '', '', ''], [6, 7, 8, 8, 8, 9]);
// console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment