用arr[pivotIndex]取代arr.splice(pivotIndex,1)[0]時報錯,錯誤訊息如下圖:
#程式碼如下,註解掉的程式碼為出錯的程式碼:
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))