有人能告诉我为什么这会产生无限循环吗?我被困住了。 也许我错过了什么?
const quickSort = function (arr) {
if (arr.length < 2) {
return arr;
}
const pivot = arr[0];
const smallerThanPivot = [];
const highterThanPivot = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] < pivot) {
smallerThanPivot.push(arr[i]);
} else {
highterThanPivot.push(arr[i]);
}
}
return [
...quickSort(smallerThanPivot),
pivot,
...quickSort(highterThanPivot),
];
};
您不会从数组中删除
pivot
,这会导致[1, 2, 3]
被分成[], [1, 2, 3]
,因为枢轴被放置到更高的部分