In this program merged two array and then sorted using temp.but this not correct method.because two array are sorted ,so method should be unique i.e. merging of two sorted i
Please find here also an implementation for merging two sorted Arrays. Actually, we could compare one by one the Array items pushing them to a new Array and when we parse completely one Array, we just concat the sliced part of the second already sorted Array.
const merge = (arr1, arr2) => {
let arr = [];
let i = 0;
let j = 0;
while (i < arr1.length || j < arr2.length) {
if (i === arr1.length) {
return arr.concat(arr2.slice(j));
}
if (j === arr2.length) {
return arr.concat(arr1.slice(i));
}
if (arr1[i] < arr2[j]) {
arr.push(arr1[i]);
i++
} else {
arr.push(arr2[j]);
j++
}
}
return arr;
}