Merge two arrays and sort the final one

前端 未结 11 996
情歌与酒
情歌与酒 2021-01-15 17:42

In an interview I was asked the following question. I am given two arrays, both of them are sorted.

BUT

Array 1 will have few -1\'s and Array 2 will have to

11条回答
  •  梦谈多话
    2021-01-15 18:27

    You could iterate arrayOne in a single loop and then arrayTwo.

    The idea is to separate the target index from the actual index. The first loop ignores -1 and and keep the target index.

    If an actual value is greater then the first value of arrayTwo, both values swapped and in arrayTwo takes a sorting place by iterating and swapping with grater values.

    Then the actual item is assigned to the target index.

    Both indices gets incremented.

    At the end all items of arrayTwo are added to arrayOne.

    function order(arrayOne, arrayTwo) {
        var i = 0, j, l = 0;
        while (i < arrayOne.length) {
            if (arrayOne[i] === -1) {
                i++;
                continue;
            }
            if (arrayTwo[0] < arrayOne[i]) {
                [arrayOne[i], arrayTwo[0]] = [arrayTwo[0], arrayOne[i]];
                j = 0;
                while (arrayTwo[j] > arrayTwo[j + 1]) {
                    [arrayTwo[j], arrayTwo[j + 1]] = [arrayTwo[j + 1], arrayTwo[j]];
                    j++;
                }
            }
            arrayOne[l++] = arrayOne[i++];
        }
        j = 0;
        while (l < arrayOne.length) {
            arrayOne[l++] = arrayTwo[j++];
        }
        return arrayOne;
    }
    
    console.log(order([3, 6, -1, 11, 15, -1, 23, 34, -1, 42], [7, 19, 38]));
    console.log(order([3, 6, -1, 11, 15, -1, 23, 34, -1, 42], [1, 9, 28]));
    console.log(order([3, 6, -1, 11, 15, -1, 23, 34, -1, 42], [1, 2, 5]));
    console.log(order([3, 6, -1, 11, 15, -1, 23, 34, -1, 42], [43, 44, 45]));
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题