js merge two sorted arrays

 defines three pointers i, j and k

Point to the end positions of the two arrays and the final merged array respectively.

Then compare the elements in the two arrays starting from the end of the array, copying the larger element to the end of the final array,

and move the corresponding pointer forward one bit. If there are remaining elements in the second array that have not been copied,

then copy them all to the front of the final array. Finally return the merged array.

<script>
    let arr1 = ['小黑','小白']
    let arr2 = ['小王','小明','小杨']
    function mergeSort([...arr1], [...arr2]) {
        let i = arr1.length - 1,j = arr2.length - 1, k = i + j + 1;
        while (i >= 0 && j >= 0) {
            if (arr1[i] < arr2[j]) {
                arr1[k--] = arr2[j--];
            } else {
                arr1[k--] = arr1[i--];
            }
        }
        while (j >= 0) {
            arr1[k--] = arr2[j--];
        }
        return arr1;
    }
    console.log('mergeSort',mergeSort(arr1,arr2));
</script>

Guess you like

Origin blog.csdn.net/Tianxiaoxixi/article/details/130079888