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
Lets implement a generic merger. Assuming that we don't know whether they are sorted ascending or descending we first need to apply a test to derive a compare function cf
. Then it's a simple recursive walk as follows;
function merger(a, b){
var cf = a[0] < a[1] || b[0] < b[1] ? (x,y) => x < y
: a[0] > a[1] || b[0] > b[1] ? (x,y) => x > y
: (x,y) => false,
mg = ([a,...as],[b,...bs]) => a !== void 0 &&
b !== void 0 ? cf(a,b) ? [a].concat(mg(as,[b,...bs]))
: [b].concat(mg([a,...as],bs))
: a === void 0 ? [b,...bs]
: [a,...as];
return mg(a,b);
}
var a = [1,2,3,5,9,10,11,12],
b = [4,6,7,8,17],
c = [9,8,7],
d = [23,11,10,4,3,2,1];
console.log(merger(a,b));
console.log(merger(c,d));
Note: The tester to decide whether ascending or descending is sloppy. It doesn't even check equity of first two. It's just to give an idea. Implementing it properly is beyond the scope of this question.