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
Based on Eric Lundgren's answer above, but this fixes a couple of major bugs and is more efficient. Worked for me in production. I included using a sort function for more complex solutions - for this simple case you can just test for a > b as in Eric's answer if you want.
function mergeSortedArray(a, b) {
var sorted = [], indexA = 0, indexB = 0;
while (indexA < a.length && indexB < b.length) {
if (sortFn(a[indexA], b[indexB]) > 0) {
sorted.push(b[indexB++]);
} else {
sorted.push(a[indexA++]);
}
}
if (indexB < b.length) {
sorted = sorted.concat(b.slice(indexB));
} else {
sorted = sorted.concat(a.slice(indexA));
}
return sorted;
}
function sortFn(a, b) {
return a - b;
}
console.log(mergeSortedArray([1,2,3,5,9],[4,6,7,8]));