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

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

提交回复
热议问题