Created
December 31, 2013 18:58
-
-
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.
This file contains 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
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