Skip to content

Instantly share code, notes, and snippets.

@devNoiseConsulting
Last active March 16, 2017 16:21
Show Gist options
  • Save devNoiseConsulting/142664d9255cc7713cf031eb559e32dd to your computer and use it in GitHub Desktop.
Save devNoiseConsulting/142664d9255cc7713cf031eb559e32dd to your computer and use it in GitHub Desktop.
Merge the following two sorted arrays into one sorted array - PhillyDev Slack #daily_programmer - 20170227
/*
Good morning! Today's daily programmer is about Array's and sorting. The
gist of this question came from a friends recent interview. It may be a
relatively familiar task. Feel free to write the solution in two
different ways to challenge yourself, or use a different language.
Please DM me with idea's for future daily problems. When you have
completed it post a link to your solution. *If you have a question about
someones solution please use a thread under their posted link.* Happy
Monday!
*/
const arrayOne = [ 2, 9, 22, 97, 167, 204 ]
const arrayTwo = [ 3, 7, 10, 22, 98, 188, 203, 205, 209, 215]
var newArray = arrayOne.concat(arrayTwo).sort(function(a, b) {
return a - b;
});
console.log(newArray);
newArray = [...arrayOne, ...arrayTwo].sort(function(a, b) {
return a - b;
});
console.log(newArray);
// Devin Fitzsimons modified solution
function mergeTwoArrays(arrayOne, arrayTwo){
let mergedArray = []
let shorterArray = arrayOne.length < arrayTwo.length ? arrayOne : arrayTwo;
let longerArray = arrayOne.length >= arrayTwo.length ? arrayOne : arrayTwo;
let len = shorterArray.length;
let k = 0;
for (let i = 0; i < len; i++){
while (shorterArray[i] >= longerArray[k]) {
mergedArray.push(longerArray[k]);
k++;
}
mergedArray.push(shorterArray[i]);
}
//mergedArray = mergedArray.concat(longerArray.slice(k));
len = longerArray.length;
for (let i = k; i < len; i++) {
mergedArray.push(longerArray[i]);
}
return mergedArray;
}
console.log(mergeTwoArrays(arrayOne, arrayTwo));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment