Sunday, August 30, 2020

Merging two sorted arrays - Big O (n+m) time complexity

 Problem : 

Merge the two sorted arrays.

Edge case : 

Array can empty

Arrays can be in different size



let getMaxLength = (input1,input2) => {
if(input1.length < input2.length) {
return input2.length;
}else {
return input1.length;
}
}
function mergeSortedArrays(input1,input2){
result = [];
let x = 0;
let y = 0;
if(!input1 || input1.length == 0){
return input2;
}
if(!input2 || input2.length == 0){
return input1;
}

let maxLength = getMaxLength(input1,input2);
while(x < input1.length && y < input2.length){
//find first smallest element between two arrays
if(input1[x] < input2[y]){
// x is smaller
result.push(input1[x++]);
}else{
// y is smaller
result.push(input2[y++]);
}
}
// add remaining array elements into result array
while(x < input1.length){
result.push(input1[x++]);
}

while(y < input2.length){
result.push(input2[y++]);
}

return result;
}

function print(result) {
for(index in result){
console.log(result[index]);
}
}
a = [1,5,7];
b = [2,6,31,44];

//print(mergeSortedArrays(a,b));
//print(mergeSortedArrays([],b));
print(mergeSortedArrays(a,[]));
//print(mergeSortedArrays([],[]));




No comments:

Post a Comment

Merging two sorted arrays - Big O (n+m) time complexity

 Problem :  Merge the two sorted arrays. Edge case :  Array can empty Arrays can be in different size let getMaxLength = ( input1 , input...