What is the difference between the code arr[pivotIndex] and arr.splice(pivotIndex,1)[0]?
黄舟
黄舟 2017-06-26 10:50:53
0
1
1097

Using arr[pivotIndex] instead of arr.splice(pivotIndex,1)[0] reports an error. The error message is as follows:

The code is as follows, the commented out code is the error code:

function quickSort (arr) {
        if (arr.length<=1) {
            return arr;
        };
        let left = [],
            right = [],
            pivotIndex = Math.floor(arr.length/2);
        //let pivot = arr[pivotIndex],   //直接获取arr[pivotIndex]赋值给pivot时报错
        let pivot = arr.splice(pivotIndex,1)[0]; //用词句代码可以正确输出排序结果
        for (let i=0; i<arr.length; i++) {
            if (arr[i] <= pivot) {
                left.push(arr[i]);
            } else {
                right.push(arr[i]);
            }
        }
        return quickSort(left).concat(pivot,quickSort(right));
    }

    console.log('纯JS快排结果: '+quickSort(newarr))
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
大家讲道理

"Please" read the documentation: https://developer.mozilla.org...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!