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

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

    Merge two arrays and create new array.

    function merge_two_sorted_arrays(arr1, arr2) {
            let i = 0;
            let j = 0;
            let result = [];
            while(i < arr1.length && j < arr2.length) {
                if(arr1[i] <= arr2[j]) {
                    result.push(arr1[i]);
                    i++;
                } else {
                    result.push(arr2[j]);
                    j++;
                }
            }
            while(i < arr1.length ) {
                result.push(arr1[i]);
                i++;
            }
            while(j < arr2.length ) {
                result.push(arr2[j]);
                j++;
            }
            console.log(result);
        }
    
    merge_two_sorted_arrays([15, 24, 36, 37, 88], [3, 4, 10, 11, 13, 20]);

提交回复
热议问题