我想實現以第一個元素爲樞軸的快速排序分區算法,我研究了最後一個元素作爲樞軸的Quicksort。有人可以告訴我在下面的僞代碼中我錯了嗎?以第一個元素爲樞紐實現快速排序分區算法
/* Taking first element of array as pivot and movig all elements
smaller than pivot left to pivot and greater tto its right */
// L is leftmost index, R is rightmost index
Partition(A[],L,R)
{
pivot = A[L]
i = L-1
for (j =L to R)
{
// If current element is smaller than or equal to pivot
if (A[j] <= pivot)
{
i++; // increment index of smaller element
swap A[i] and A[j]
}
}
swap A[i + 1] and A[L])
return (i + 1)
}
quicksort是用C++編寫的。 Qsort是C中的快速排序。 –
你確定*你錯了嗎?什麼讓你有那個想法?你有沒有嘗試向你的[橡皮鴨]解釋僞代碼(https://en.wikipedia.org/wiki/Rubber_duck_debugging)? –
如果你知道pivot元素的最後一個元素的正確代碼,那麼你可以做的一件事就是交換第一個元素和最後一個元素,並用最後一個元素運行代碼。在這方面需要很少的努力。 –