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

后端 未结 24 956
我寻月下人不归
我寻月下人不归 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: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]);
    

提交回复
热议问题