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

后端 未结 24 966
我寻月下人不归
我寻月下人不归 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-18 14:35

    I have been working on it for while now, and I have found a good solution. I didn't came up with this algorithm, but I implemented it properly in Javscript. I have tested it with massive number of array, and I have included comments so it's easier to understand. Unlike many other solutions, this one of the most efficient one, and I have included some tests. You run the code to verify that works. Time Complexity of a this solution is O(n)

    function mergeTwoSortedArraay(rightArr, leftArr) {
     // I decided to call frist array "rightArr" and second array "leftArr"
      var mergedAr = [], sizeOfMergedArray = rightArr.length + leftArr.length; // so if rightArray has 3 elements and leftArr has 4, mergedArray will have 7.
       var r = 0, l =0; // r is counter of rightArr and l is for leftArr;
       for(var i =0; i< sizeOfMergedArray; ++i) {
           if(rightArr[r] >= leftArr[l] || r >= rightArr.length) { // r >= rightArr.length when r is equal to greater than length of array, if that happens we just copy the reaming 
            // items of leftArr to mergedArr
    
                mergedAr[i] = leftArr[l];
                l++;
           } else { 
               mergedAr[i] = rightArr[r];
               r++;
           }
       }
       return mergedAr;
    }
    // few tests
    console.log(mergeTwoSortedArraay([ 0, 3, 4, 7, 8, 9 ],[ 0, 4, 5, 6, 9 ]));
    
    console.log(mergeTwoSortedArraay([ 7, 13, 14, 51, 79 ],[ -356, 999 ]));
    console.log(mergeTwoSortedArraay([ 7, 23, 64, 77 ],[ 18, 42, 45, 90 ]));

提交回复
热议问题