猿问

javascript 快速排序 无缘错误,我哪里错了?

学习算法 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]));

炎炎设计
浏览 487回答 1
1回答

隔江千里

死循环,堆栈溢出了。right数组有两项,9,8.递归执行的时候始终是9,8.因为此时mid是8,ara[i]始终>=mid,right数组始终是9,8.就死循环了。正确写法如下:function quickSort(arr){&nbsp; &nbsp; var len;&nbsp; &nbsp; len=arr.length;&nbsp; &nbsp; if (len <= 1) {&nbsp; &nbsp; &nbsp; &nbsp; return arr; //如果数组只有一个数,就直接返回;&nbsp; &nbsp; }&nbsp; &nbsp; var midlen = Math.floor(len/2);&nbsp; &nbsp; // var mid = arr[midlen];&nbsp; &nbsp; var mid = arr.splice(midlen,1)[0];&nbsp; &nbsp; // console.log(mid);&nbsp; &nbsp; var left = [];&nbsp; &nbsp; var right = [];&nbsp; &nbsp; for (var i = 0,len=arr.length; i < len; i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (arr[i] <= mid) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; left.push(arr[i]);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; right.push(arr[i]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; // console.log(left.concat([mid],right));&nbsp; &nbsp; return quickSort(left).concat([mid], quickSort(right));}//testconsole.log(quickSort([9, 2, 8, 5, 1]));//输出:[ 1, 2, 5, 8, 9 ]
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答