学习算法 javascript 实现,写一个简单的快速排序,在浏览器中一直报错。代码:
function quickSort(arr){ var len; len=arr.length; if (len <= 1) { return arr; //如果数组只有一个数,就直接返回; } var midlen = Math.floor(len/2); var mid = arr[midlen]; // console.log(mid); var left = []; var right = []; for (var i = 0; i < len; i++) { if (arr[i] < mid) { left.push(arr[i]); } else { right.push(arr[i]); } } // console.log(left.concat([mid],right)); return quickSort(left).concat([mid], quickSort(right)); } //test console.log(quickSort([9, 2, 8, 5, 1]));
javascript Quick sort No error, where did I go wrong? -PHP Chinese website Q&A-javascript quick sort No error, where did I go wrong? -PHP Chinese website Q&A
Let’s take a look and learn.
死循环,堆栈溢出了。right数组有两项,9,8.递归执行的时候始终是9,8.
因为此时mid是8,ara[i]始终>=mid,right数组始终是9,8.就死循环了。
正确写法如下: