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
How about something like this?
Since a and b are both sorted we only need to consider the top or first item of each array when adding. Note that this method will modify both a and b during execution, this may not be what you want, in which case you can add this code at the start:
var tempA = a.slice();
var tembB = b.slice();
This will make copies of the array which you can then use instead of a and b in the function below:
function mergeSortedArray(a,b){
var tempArray = [];
while(a.length || b.length) {
if(typeof a[0] === 'undefined') {
tempArray.push(b[0]);
b.splice(0,1);
} else if(a[0] > b[0]){
tempArray.push(b[0]);
b.splice(0,1);
} else {
tempArray.push(a[0]);
a.splice(0,1);
}
}
return tempArray;
}
console.log(mergeSortedArray([4,6,7,8], [1,2,3,5,9]));
Without using splice at all, try something like this:
function mergeSortedArray(a,b){
var tempArray = [];
var currentPos = {
a: 0,
b: 0
}
while(currentPos.a < a.length || currentPos.b < b.length) {
if(typeof a[currentPos.a] === 'undefined') {
tempArray.push(b[currentPos.b++]);
} else if(a[currentPos.a] > b[currentPos.b]){
tempArray.push(b[currentPos.b++]);
} else {
tempArray.push(a[currentPos.a++]);
}
}
return tempArray;
}
console.log(mergeSortedArray([1,2,3,5,9],[4,6,7,8]));