您现在的位置是:课程教程文章
js如何合并两个有序数组
2023-12-13 22:58课程教程文章 人已围观
1、新建空数组res存储最终排序后的数组。
2、比较两个有序数组的头部,年轻人出队推进res。
3、如果两个数组仍然值得,重复第二步。
实例
Array.prototype.mergeSort=function(){ constrec=(arr)=>{ if(arr.length===1){ returnarr; } constmid=Math.floor(arr.length/2); constleft=arr.slice(0,mid); constright=arr.slice(mid,arr.length); constorderLeft=rec(left); constorderRight=rec(right); constres=[]; while(orderLeft.length||orderRight.length){ if(orderLeft.length&&orderRight.length){ res.push( orderLeft[0]<orderRight[0]?orderLeft.shift():orderRight.shift() ); }elseif(orderLeft.length){ res.push(orderLeft.shift()); }elseif(orderRight.length){ res.push(orderRight.shift()); } } returnres; }; constres=rec(this); res.forEach((n,i)=>{ this[i]=n; }); }; constarr=[5,4,3,2,1]; arr.mergeSort();
以上就是js合并两个有序数组的方法,希望对大家有所帮助。更多js学习指路:js教程
推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。
课程教程:js如何合并两个有序数组下一篇:没有了