Home > Software engineering >  Merging two sorted arrays using two pointers method
Merging two sorted arrays using two pointers method

Time:08-29

I am trying to solve a leetcode question.
The question is to merge two sorted arrays :

Input:
arr1 = [2,4,7,9 ]
arr2 = [1,3,5,11,13]

Output [1,2,3,4,5,7,9,11,13]

My solution looks something like :

function mergeTwoSortedArrays(arr1, arr2){
    let newArr = [];
    let newArrSize = (arr1.length   arr2.length) - 1;
    let i = arr1.length - 1;
    let j = arr2.length - 1;

    while(i >= 0 || j>=0){
        if(arr1[i] > arr2[j]){
            newArr[newArrSize] = arr1[i];
            newArrSize--;
            i--;
        }
        if(arr2[j] > arr1[i]){
            newArr[newArrSize] = arr2[j];
            newArrSize--;
            j--;
        }
    }
    return newArr;
}
    let arr1 = [2,4,7,9 ]
    let arr2 = [1,3,5,11,13];
    console.log(mergeTwoSortedArrays(arr1,arr2));

The problem here is that it goes into an infinite loop and exits. I think the while codition am using is wrong but what's wrong ?

CodePudding user response:

You could just use concat and sort, but if you're supposed to implement it yourself:

function mergeTwoSortedArrays(arr1, arr2){
    let newArr = [];
    let i = arr1.length;
    let j = arr2.length;
    let newArrSize = i   j;

    while(newArrSize > 0){
        if(typeof arr2[j-1] == 'undefined' || (arr1[i-1] > arr2[j-1])){
            console.log('-', i, arr1[i-1])
            newArr[newArrSize-1] = arr1[i-1];
            newArrSize--;
            i--;
        }else if(typeof arr1[i-1] == 'undefined' || (arr2[j-1] > arr1[i-1])){
            console.log('j', j, arr2[j-1])
            newArr[newArrSize-1] = arr2[j-1];
            newArrSize--;
            j--;
        }
    }
    return newArr;
}

CodePudding user response:

Use ... spread operator to merge and sort() funtion to sort arrays

var merged = [...arr1, ...arr2]
merged.sort((a,b)=>a-b)
console.log(merged)
  • Related