Quick actions

cmd+k|ctrl+k

Navigation

Languages

mergeSortedArrays

Snippet info

Language

JavaScript

Visibility

public

Author

rovanova

Created

2020-03-20T15:42:40Z

Updated

2020-03-20T15:58:04Z

function mergeSortedArrays(arr1, arr2) {
var newSortedArray = [];
let i=0, j=0;
while(i<arr1.length && j<arr2.length){
if(arr1[i]<arr2[j]){
  newSortedArray.push(arr1[i]);
  i++;
}
else{
  newSortedArray.push(arr2[j]);
  j++;
}
}
while(i<arr1.length){
    newSortedArray.push(arr1[i]);
    i++;
}
while(j<arr2.length){
    newSortedArray.push(arr2[j]);
    j++;
}

console.log(newSortedArray);
}

mergeSortedArrays([0,3,4,31], [4,6,30]);
//[ 0,3,4,4,6,30,31]

//Idea of i for 1st array and j for 2nd array
/*
About inputs, 
* Empty arrays
* One of them is Empty
* Array contains numbers or characters 
1.Compare i and j values of both arrays
2.Add whichever is lower to newSortedArray and increment index 
3.Repeat this process till one of the array ends or both if of equal length
*/
INFO