Skip to content

Instantly share code, notes, and snippets.

@basil2style
Created May 18, 2021 13:42
Show Gist options
  • Save basil2style/280fb9c6c7efe63963565b08a9abdd6a to your computer and use it in GitHub Desktop.
Save basil2style/280fb9c6c7efe63963565b08a9abdd6a to your computer and use it in GitHub Desktop.
Merge two sorted arrays into thrid array with O(n+m)
//Merge two sorted arrays into thrid array with O(n+m)
var merge = function (nums1, m, nums2, n) {
let i = 0,
j = 0,
k = 0;
let arr = [];
while (i < m && j < n) {
if (nums1[i] < nums2[j]) {
arr[k] = nums1[i];
i = i+1;
} else {
arr[k] = nums2[j];
j = j+1;
}
k++;
}
console.log("I: "+i+",J :"+j);
while(i<m) {
arr[k]= nums1[i];
i++; k++;
}
console.log("I: "+i+",J :"+j);
while(j<n) {
arr[k]= nums2[j];
j++; k++;
}
return arr;
};
let nums1 = [1, 2, 3, 0, 0, 0],
m = 3,
nums2 = [2, 5, 6],
n = 3;
// let nums1 = [1], m = 1, nums2 = [], n = 0;
console.log(merge(nums1, m, nums2, n));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment