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

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

    Based on Eric Lundgren's answer above, but this fixes a couple of major bugs and is more efficient. Worked for me in production. I included using a sort function for more complex solutions - for this simple case you can just test for a > b as in Eric's answer if you want.

    function mergeSortedArray(a, b) {
        var sorted = [], indexA = 0, indexB = 0;
    
        while (indexA < a.length && indexB < b.length) {
            if (sortFn(a[indexA], b[indexB]) > 0) {
                sorted.push(b[indexB++]);
            } else {
                sorted.push(a[indexA++]);
            }
        }
    
        if (indexB < b.length) {
            sorted = sorted.concat(b.slice(indexB));
        } else {
            sorted = sorted.concat(a.slice(indexA));
        }
    
        return sorted;
    }
    
    function sortFn(a, b) {
        return a - b;
    }
    
    console.log(mergeSortedArray([1,2,3,5,9],[4,6,7,8]));
    

提交回复
热议问题