Code Fragment: QuickSort



template <typename Object, typename Sequence>
class QuickSort {					// QuickSort class
protected: 						// recursive utility
  void quickSortStep(Sequence& S, int leftBound, int rightBound);
public:
  void quickSort(Sequence& S);				// main entry point
};

template <typename Object, typename Sequence>
void QuickSort<Object, Sequence>:: 			// recursive portion
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);
}

template <typename Object, typename Sequence>
void QuickSort<Object, Sequence>::
quickSort(Sequence& S) {				// main entry point
  if (S.size() <= 1) return;				// 0 or 1 elements
  quickSortStep(S, 0, S.size()-1);			// call sort utility
}