//lib_test.h
//head file of quick sort
//users should realise operator > and <
#ifndef lib_test_h
#define lib_test_h
template<class t>
class sort
{
public:
static void myqsort(t a[], int p, int r);
static void myqsortnorecur(t a[], int p, int r);
private:
static int partition(t a[], int p, int r);
static void exchange(t a[], int i, int j);
};
#endif
lib_test.cc:
//lib_test.cc
#include <iostream>
#include <stack>
#include"stdlib.h"
#include <time.h>
#include "lib_test.h"
using namespace std;
template<class t>
void sort<t>::exchange(t a[], int i, int j)
{
t temp = a[i];
a[i] = a[j];
a[j] = temp;
return;
}
template<class t>
int sort<t>::partition(t a[],int p,int r)
{
int i = p;
int j = p-1;
t ref = a[p];
int refid = p;
srand((unsigned)time(null));
refid = (rand() % (r-p+1))+ p;
//cout<<refid<<endl;
ref = a[refid];
for(; i<=r; i++)
{
if(a[i] < ref)
{
j++;
exchange(a, i, j);
if(j == refid)
{
refid = i;
}
}
}
exchange(a, j+1, refid);
return j+1;
}
template<class t>
void sort<t>::myqsort(t a[],int p,int r)
{
int q = 0;
if(p<r)
{
q = partition(a, p, r);
myqsort(a, p, q-1);
myqsort(a, p+1, r);
}
return;
}
template<class t>
void sort<t>::myqsortnorecur(t a[], int p, int r)
{
int start = p;
int end = r;
int mid = 0;
std::stack<int> sortstk;
sortstk.push(p);
sortstk.push(r);
while(!sortstk.empty())
{
end = sortstk.top();
sortstk.pop();
start = sortstk.top();
sortstk.pop();
if(start < end)
{
mid = partition(a, start, end);
sortstk.push(start);
sortstk.push(mid -1);
sortstk.push(mid + 1);
sortstk.push(end);
}
}
}