how to merge two sorted array in one sorted array in JavaScript without using sort()

后端 未结 24 1276
我寻月下人不归
我寻月下人不归 2021-01-18 13:57

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

24条回答
  •  佛祖请我去吃肉
    2021-01-18 14:25

    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]));

提交回复
热议问题