<pre name="code" class="cpp">//Data.h
#ifndef _DATA_H_
#define _DATA_H_
#include <IOSTREAM>
using namespace std;
template<class Type>
class Data
{
public:
Data(Type* p, int low, int high);
Data(const Data& data);
Data()
{
}
const Data operator=(const Data& data);
friend ostream& operator<< <Type>(ostream& os, const Data<Type>& data);
~Data()
{
}
public:
Type * arr;
int m_low;
int m_high;
};
#include "Data.cpp"
#endif //_DATA_H_
//Data.cpp
#ifndef _DATA_CPP_
#define _DATA_CPP_
#include "Data.h"
template<class Type>
const Data<Type> Data<Type>::operator=( const Data<Type>& data )
{
arr = data.arr;
m_low = data.m_low;
m_high = data.m_high;
return *this;
}
template<class Type>
Data<Type>::Data( const Data<Type>& data ) : arr(data.arr), m_low(data.m_low), m_high(data.m_high)
{
}
template<class Type>
Data<Type>::Data( Type* p, int low, int high ) :arr(p),m_low(low), m_high(high)
{
}
template<class Type>
ostream& operator << (ostream& os, const Data<Type>& data)
{
for (int i = data.m_low; i <= data.m_high; ++i)
{
os << data.arr[i];
}
return os;
}
#endif //_DATA_CPP_
//show_main.cpp
#include <IOSTREAM>
#include "Data.h"
#include <stack>
using namespace std;
template <class Type>
int partition(Type arr[], int low, int high)
{
Type x = arr[low];
while (low<high)
{
while (low < high && arr[high]>=x)--high;
arr[low] = arr[high];
while (low < high && arr[low] <= x)++low;
arr[high] = arr[low];
}
arr[low] = x;
return low;
}
template <class Type>
void quickSort(Type arr[], int low, int high)
{
if (low < high)
{
int pov = partition(arr, low, high);
quickSort(arr, low, pov-1);
quickSort(arr, pov+1, high);
}
}
template<class Type>
void NonRecurQsort(Type arr[], int low, int high)
{
stack<Data<Type> > s;
if (!arr || low >= high)
return ;
int pov = 0;
Data<Type> data(arr, low, high);
s.push(data);
Data<Type> temp;
Data<Type> right, left;
while (!s.empty())
{
temp = s.top();
s.pop();
pov = partition(temp.arr, temp.m_low, temp.m_high);
//产生新的手头工作,如果满足条件,则放入
right = Data<Type>(temp.arr, temp.m_low, pov-1);
if (temp.m_low<pov-1)
s.push(right);
left = Data<Type>(temp.arr, pov+1, temp.m_high);
if (pov+1 < temp.m_high)
s.push(left);
}
}
int main()
{
int arr[10] = {2, 5, 8, 3, 0, 4, 9, 1, 7, 6};
// NonRecurQsort<int>(arr, 0, 9); //success
NonRecurQsort(arr, 0, 9);//success
for (int i=0; i<10; i++)
cout << arr[i] << " " ;
cout << endl;
return 0;
}
非递归实现快速排序算法
最新推荐文章于 2022-03-17 16:53:33 发布