- #1
abacus
- 21
- 0
My textbook has the following code as a Quick Sort. It also discusses a randomized quick sort which should have a faster run time, but doesn't show the code for it. What would the code be like? Is only the pivot changed?
http://cpp.datastructures.net/source/ch10/CPP/Sort.h-QuickSort.html
Code:
void quickSortStep(Sequence& S, int leftBound, int rightBound) {
if (leftBound >= rightBound) return; // 0 or 1 elements
Object pivot = S.atRank(rightBound).element(); // select last as pivot
int leftIndex = leftBound; // will scan rightward
int rightIndex = rightBound - 1; // will scan leftward
while (leftIndex <= rightIndex) {
while ((leftIndex <= rightIndex) && // scan right to larger
S.atRank(leftIndex).element() <= pivot)
leftIndex++;
while ((rightIndex >= leftIndex) && // scan left to smaller
S.atRank(rightIndex).element() >= pivot)
rightIndex--;
if (leftIndex < rightIndex) // both elements found
S.swapElements(S.atRank(leftIndex), S.atRank(rightIndex));
} // until indices cross
// pivot at leftIndex
S.swapElements(S.atRank(leftIndex), S.atRank(rightBound));
quickSortStep(S, leftBound, leftIndex-1); // recur on both sides
quickSortStep(S, leftIndex+1, rightBound);
}
http://cpp.datastructures.net/source/ch10/CPP/Sort.h-QuickSort.html