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

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

提交回复
热议问题