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

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

    Please find here also an implementation for merging two sorted Arrays. Actually, we could compare one by one the Array items pushing them to a new Array and when we parse completely one Array, we just concat the sliced part of the second already sorted Array.

    const merge = (arr1, arr2) => {
        let arr = [];
        let i = 0;
        let j = 0;
        while (i < arr1.length || j < arr2.length) {
            if (i === arr1.length) {
                return arr.concat(arr2.slice(j));
            }
            if (j === arr2.length) {
                return arr.concat(arr1.slice(i));
            }
            if (arr1[i] < arr2[j]) {
                arr.push(arr1[i]);
                i++
            } else {
                arr.push(arr2[j]);
                j++
            }
        }
        return arr;
    }
    

提交回复
热议问题