//FILE: QuickSort.h
//AUTHOR: nshe
//DATE: 2009.01.02
#ifndef _QUICKSORT_H_
#define _QUICKSORT_H_
/*
enum SORT_TYPE { ASCEND, DESCEND};
template<class T>
int PartitionAscend(T array[], int low, int high)
{
T pivot = array[low];
while(low < high)
{
while(low < high && array[high] >= pivot)
--high;
if( low < high )
array[low] = array[high];
while(low < high && array[low] <= pivot)
++low;
if( low < high )
array[high] = array[low];
}
array[low] = pivot;
return low;
}
template<class T>
int PartitionDescend(T array[], int low, int high)
{
T pivot = array[high];
while(low < high)
{
while(low < high && array[low] >= pivot)
++low;
array[high] = array[low];
while(low < high && array[high] <= pivot)
--high;
array[low] = array[high];
}
array[high] = pivot;
return high;
}
template<class T>
void QSortAscend(T array[], int low, int high)
{
if(low<high)
{
int pivot = PartitionAscend(array, low, high);
QSortAscend(array, low, pivot-1);
QSortAscend(array, pivot+1, high);
}
else
return;
}
template<class T>
void QSortDescend(T array[], int low, int high)
{
if(low<high)
{
int pivot = PartitionDescend(array, low, high);
QSortDescend(array, low, pivot-1);
QSortDescend(array, pivot+1, high);
}
else
return;
}
template<class T>
void QuickSort(T array[], int n, SORT_TYPE ST = ASCEND)
{
if(ST == ASCEND)
QSortAscend(array, 0, n-1);
else
QSortDescend(array, 0, n-1);
}
*/
template<class T>
int Partition(T array[], int low, int high)
{
int i = low-1;
int j;
T tmp;
for(j=low; j<high; ++j)
{
if(array[j] < array[high])
{
++i;
if( i != j )
{
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
}
if(high != i+1)
{
tmp = array[i+1];
array[i+1] = array[high];
array[high] = tmp;
}
return i+1;
}
template<class T>
void QSort(T array[], int low, int high)
{
if(low < high)
{
int pivot = Partition(array, low, high);
QSort(array, low, pivot-1);
QSort(array, pivot+1, high);
}
}
template<class T>
void QuickSort(T array[], int size)
{
QSort(array,0,size-1);
}
#endif
//FILE: test.cpp
//AUTHOR: nshe
//DATE: 2009.01.02
#include "QuickSort.h"
#define MAX 1000000
#include <iomanip.h>
#include <vector>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
int i,vec[MAX];
srand(time(NULL));
for( i = 0; i < MAX; ++i)
vec[i] = rand();
for( i = 0; i < MAX; ++i)
{
cout<<setw(5)<<vec[i]<<" ";
if((i+1)%10 == 0)
cout<<endl;
}
cout<<endl<<endl;
///*
QuickSort(vec, MAX);//, ASCEND);
for( i = 0; i < MAX; ++i)
{
cout<<setw(5)<<vec[i]<<" ";
if((i+1)%10 == 0)
cout<<endl;
}
cout<<endl<<endl;
//*/
/*
QuickSort(vec, MAX, DESCEND);
for( i = 0; i < MAX; ++i)
{
cout<<setw(5)<<vec[i]<<" ";
if((i+1)%10 == 0)
cout<<endl;
}
*/
return 0;
}