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

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

    Merge Two Sorted Arrays

    function merge(arr1, arr2) {
        const arr = [];
    
        while (arr1.length && arr2.length) {
            if (arr1[0] < arr2[0]) {
                arr.push(arr1.shift());
            } else {
                arr.push(arr2.shift());
            }
        }
        return [...arr, ...arr1, ...arr2];
    }
    

    * If you want to merge the arrays in-place, clone each array and use it in the while loop instead.

    Example: clonedArr1 = [...arr1];

提交回复
热议问题