[英]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.