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

后端 未结 24 1241
我寻月下人不归
我寻月下人不归 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:39

    I wanted to add a solution that included an array with an initialized size, so that there are no copies of the arrays made outside of the new sorted array. This means no calls to slice or extra concat:

    function defaultComparator(a, b) {
        return a - b;
    }
    
    function mergeSortedArray(arrA, arrB, comparator) {
        var _comparator = (typeof comparator === 'undefined')
            ? defaultComparator
            : comparator;
        var idxA = 0, idxB = 0, idxS = 0;
        var arrSorted = new Array(arrA.length + arrB.length);
        while (idxA < arrA.length || idxB < arrB.length) {
            if (idxA >= arrA.length)
                arrSorted[idxS++] = arrB[idxB++];
            else if (idxB >= arrB.length)
                arrSorted[idxS++] = arrA[idxA++];
            else if (_comparator(arrA[idxA], arrB[idxB]) <= 0)
                arrSorted[idxS++] = arrA[idxA++];
            else
                arrSorted[idxS++] = arrB[idxB++];
        }
        return arrSorted;
    }
    
    console.log(mergeSortedArray([0,2,3,5,9],[-3,1,5,6,9.5]));
    console.log(mergeSortedArray(
        [{ n: 0 }, { n: 2 }, { n: 3 }, { n: 5 }, { n: 9 }],
        [{ n: -2 }, { n: 0 }, { n: 4 }],
        function(a, b) { return a.n - b.n; }
    ))

提交回复
热议问题