SOURCE FILE: qSort.cpp


void ChoosePivot(dataType A[], int F, int L);
// ---------------------------------------------------------
// Chooses a pivot for quicksortÕs partition algorithm and 
// swaps it with the first item in an array.
// Precondition: A[F..L] is an array; F <= L.
// Postcondition: A[F] is the pivot.
// ---------------------------------------------------------
// Implementation left as an exercise.

void Partition(dataType A[], int F, int L, int& PivotIndex)
// ---------------------------------------------------------
// Partitions an array for quicksort.
// Precondition: A[F..L] is an array; F <= L.
// Postcondition: Partitions A[F..L] such that:
//    S1 = A[F..PivotIndex-1] <  Pivot
//         A[PivotIndex]      == Pivot
//    S2 = A[PivotIndex+1..L] >= Pivot
// Calls: ChoosePivot and Swap.
// ---------------------------------------------------------
{
   ChoosePivot(A, F, L);      // place pivot in A[F]
   dataType Pivot = A[F];     // copy pivot

   // initially, everything but pivot is in unknown
   int LastS1 = F;            // index of last item in S1
   int FirstUnknown = F + 1;  // index of first item in 
                              // unknown

   // move one item at a time until unknown region is empty
   for (; FirstUnknown <= L; ++FirstUnknown)
   {  // Invariant: A[F+1..LastS1] < Pivot
      //            A[LastS1+1..FirstUnknown-1] >= Pivot

      // move item from unknown to proper region
      if (A[FirstUnknown] < Pivot)
      {  // item from unknown belongs in S1
         ++LastS1;
         Swap(A[FirstUnknown], A[LastS1]);
      }  // end if

      // else item from unknown belongs in S2
   }  // end for

   // place pivot in proper position and mark its location
   Swap(A[F], A[LastS1]);
   PivotIndex = LastS1;
}  // end Partition

void Quicksort(dataType A[], int F, int L)
// ---------------------------------------------------------
// Sorts the items in an array into ascending order.
// Precondition: A[F..L] is an array.
// Postcondition: A[F..L] is sorted.
// Calls: Partition.
// ---------------------------------------------------------
{
   int PivotIndex;

   if (F < L)
   {  // create the partition: S1, Pivot, S2
      Partition(A, F, L, PivotIndex);

      // sort regions S1 and S2
      Quicksort(A, F, PivotIndex-1);
      Quicksort(A, PivotIndex+1, L);
   }  // end if
}  // end Quicksort