使用 JavaScript 将两个排序数组合并为一个排序数组
问题
我们需要编写一个JavaScript函数,该函数接受两个已排序的数字数组,我们的函数应该将两个数组的所有元素合并到一个新数组中,并返回以相同顺序排序的新数组。
示例
以下是代码-
const arr1 = [1, 3, 4, 5, 6, 8]; const arr2 = [4, 6, 8, 9, 11]; const mergeSortedArrays = (arr1 = [], arr2 = []) => { const res = []; let i = 0; let j = 0; while(i < arr1.length && j < arr2.length){ if(arr1[i] < arr2[j]){ res.push(arr1[i]); i++; }else{ res.push(arr2[j]); j++; } }; while(i < arr1.length){ res.push(arr1[i]); i++; }; while(j < arr2.length){ res.push(arr2[j]); j++; }; return res; }; console.log(mergeSortedArrays(arr1, arr2));输出结果
[ 1, 3, 4, 4, 5, 6, 6, 8, 8, 9, 11 ]