[英]javascript quicksort different output than expected
我正在学习快速排序,我写了这段代码(复制了一半),但由于某种原因它不起作用。 我要做的就是使用快速排序按升序对数组进行排序。
const arr = [5, 2, 4, 2, 1, 9, 5, 8, 7, 4];
const quickSort = (arr, left = 0, right = arr.length - 1) => {
if (left < right) {
let pivotIndex = pivot(arr, left, right)
//LEFT HALF
quickSort(arr, left, pivotIndex - 1);
//RIGHT HALF
quickSort(arr, pivotIndex + 1, right);
}
return arr;
}
Pivot function
const pivot = (arr, start = 0, end = arr.length - 1) => {
const swap = (arr, i, j) => {
[arr[i], arr[j]] = [arr[j], arr[i]];
}
let pivot = arr[start];
let swapIndex = start;
for (let i = 1; i < end; i++) {
if (arr[i] < pivot) {
swapIndex++;
swap(arr, swapIndex, i);
}
}
swap(arr, start, swapIndex)
return swapIndex
}
Output
[
1, 5,
8, 7,
undefined, undefined,
9, undefined,
undefined, 2,
2, 4,
4, 5
]
请告诉我错误和解决方案。 我了解快速排序的工作原理,但在理解代码逻辑方面仍有一些困难。
pivot中的逻辑是错误的。
让我们看一下 pivot 的第一次迭代:
start = 0;
end = 9;
pivot = 5;
swapIndex = 0;
i = 1;
if(arr[i] < pivot)
{
swapIndex++;
swap(arr, swapIndex, i)
}
// this evaluates to:
if(2 < 5)
{
swapIndex = 1;
swap(arr, swapIndex, 1);
}
所以不会发生交换。
下一个i
也会发生同样的情况吗?
if(4 < 5)
{
swapIndex = 2;
swap(arr, swapIndex, 2);
}
是的,接下来的两个i
也是如此。 下一次交换的机会是在最后,当i
是 9 时,但测试是针对i < end
,所以交换永远不会发生。
我相信从较大的索引来看 pivot 更常见,从头到尾只有 pivot。
const pivot = (arr, start = 0, end = arr.length - 1) => { const swap = (arr, i, j) => { [arr[i], arr[j]] = [arr[j], arr[i]]; }; let pivot = arr[end]; let swapIndex = start-1; for (let i = start; i <= end-1; i++) { if (arr[i] < pivot) { swapIndex++; swap(arr, swapIndex, i); } } swap(arr, swapIndex+1, end) return swapIndex+1 } let inp = [5, 2, 4, 2, 1, 9, 5, 8, 7, 4]; const quickSort = (arr, left = 0, right = arr.length - 1) => { if (left < right) { let pivotIndex = pivot(arr, left, right) //LEFT HALF quickSort(arr, left, pivotIndex-1); //RIGHT HALF quickSort(arr, pivotIndex + 1, right); } return arr; } console.log(quickSort(inp).join(','));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.