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

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

    Merge two arrays and create new array.

    function merge_two_sorted_arrays(arr1, arr2) {
            let i = 0;
            let j = 0;
            let result = [];
            while(i < arr1.length && j < arr2.length) {
                if(arr1[i] <= arr2[j]) {
                    result.push(arr1[i]);
                    i++;
                } else {
                    result.push(arr2[j]);
                    j++;
                }
            }
            while(i < arr1.length ) {
                result.push(arr1[i]);
                i++;
            }
            while(j < arr2.length ) {
                result.push(arr2[j]);
                j++;
            }
            console.log(result);
        }
    
    merge_two_sorted_arrays([15, 24, 36, 37, 88], [3, 4, 10, 11, 13, 20]);

    0 讨论(0)
  • 2021-01-18 14:36

    Please find here also an implementation for merging two sorted Arrays. Actually, we could compare one by one the Array items pushing them to a new Array and when we parse completely one Array, we just concat the sliced part of the second already sorted Array.

    const merge = (arr1, arr2) => {
        let arr = [];
        let i = 0;
        let j = 0;
        while (i < arr1.length || j < arr2.length) {
            if (i === arr1.length) {
                return arr.concat(arr2.slice(j));
            }
            if (j === arr2.length) {
                return arr.concat(arr1.slice(i));
            }
            if (arr1[i] < arr2[j]) {
                arr.push(arr1[i]);
                i++
            } else {
                arr.push(arr2[j]);
                j++
            }
        }
        return arr;
    }
    
    0 讨论(0)
  • 2021-01-18 14:36
    function mergeSortedArray(a, b){
    var merged = [], 
    aElm = a[0],
      bElm = b[0],
      i = 1,
      j = 1;
     if(a.length ==0)
       return b;
         if(b.length ==0)
           return a;
          while(aElm || bElm){
            if((aElm && !bElm) || aElm < bElm){
               merged.push(aElm);
                  aElm = a[i++];
             }   
             else {
                    merged.push(bElm);
                    bElm = b[j++];
                  }
          }
          return merged;
        }
        
       //check
    
     > mergeSortedArray([2,5,6,9], [1,2,3,29]);
     = [1, 2, 2, 3, 5, 6, 9, 29]
    

    hope this helps, please correct me if i am wrong anywhere.

    0 讨论(0)
  • 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; }
    ))

    0 讨论(0)
  • 2021-01-18 14:41

    It may not be the cleanest approach but give it a try.

    function mergeSortedArrays(array1, array2){
      const mergedArray = [];
      let array1Item = array1[0];
      let array2Item = array2[0];
      let i = 1;
      let j = 1;
     
      if(array1.length === 0) {
        return array2;
      }
      if(array2.length === 0) {
        return array1;
      }
    
      while (array1Item || array2Item){
       if(array2Item === undefined || array1Item < array2Item){
         mergedArray.push(array1Item);
         array1Item = array1[i];
         i++;
       }   
       else {
         mergedArray.push(array2Item);
         array2Item = array2[j];
         j++;
       }
      }
      return mergedArray;
    }
    
    mergeSortedArrays([0,3,4,31], [3,4,6,30]);
    
    0 讨论(0)
  • 2021-01-18 14:43

    Hey I ran everyone's code from above against a simple .concat() and .sort() method. With both large and small arrays, the .concat() and .sort() completes in less time, significantly.

    console.time("mergeArrays");
    mergeArrays([1,2,3,5,9],[4,6,7,8])
    console.timeEnd("mergeArrays");
    //mergeArrays: 0.299ms
    
    console.time("concat sort");
    [1,2,3,5,9].concat([4,6,7,8]).sort();
    console.timeEnd("concat sort");
    //concat sort:0.018ms
    

    With arrays of 10,000 size, the difference is even larger with the concat and sort running even faster than before (4.831 ms vs .008 ms).

    What's happening in javascript's sort that makes it faster?

    0 讨论(0)
提交回复
热议问题