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

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

    Shortest Merge Sorted arrays without sort() plus, without using third temp array.

    function mergeSortedArray (a, b){
      let index = 0;
    
      while(b.length > 0 && a[index]) {
        if(a[index] > b[0]) {
          a.splice(index, 0, b.shift());
        }
        index++;
      }
      return [...a, ...b];
    }
    mergeSortedArray([1,2,3,5,9],[4,6,7,8])
    

提交回复
热议问题