//  File: quicksort3.C
//
//  template "implementation" for Quicksort

#include "quicksort3.h"


//==========================================================================
// Templates for local function prototypes
//

template <class DATA>
static int partition(DATA A[], int low, int high) ;

template <class DATA>
static void RecQuickSort(DATA A[], int low, int high) ;


//==========================================================================
// Templates for function definitions
//

template <class DATA>
static int partition(DATA A[], int low, int high) {
   DATA x, temp ;
   int i, j ;

   i = low - 1;
   j = high + 1;
   x = A[low] ;

   while (true) {

      // Find an element less than x
      do {
         j = j - 1;
      } while (A[j] > x) ;

      // Find an element greater than x
      do {
         i = i + 1;
      } while (A[i] < x);

      // swap smaller and bigger elements, if needed
      //
      if (i < j) {
         temp = A[j] ;
         A[j] = A[i] ;
         A[i] = temp ;
      } else {
         return j;
      }
    }
}


template <class DATA>
static void RecQuickSort(DATA A[], int low, int high) {
   int q ;

   if (low >= high) return ;

   q = partition(A, low, high) ;

   RecQuickSort(A, low, q) ;
   RecQuickSort(A, q + 1, high) ;
}


template <class DATA>
void QuickSort(DATA A[], int n) {

   RecQuickSort(A, 0, n-1) ;
}
