自己写的C++快速排序代码
//Quick排序
class Quick_Sort
{
public:
Quick_Sort();
~Quick_Sort();
public:
template <class T>
static int Partition(T *arry, const int start, const int finish);
template <class T>
static void QuickSort(T *arry, const int start, const int finish);
template <class T>
static void swap (T* _target, T* _source, const unsigned size);
};
Quick_Sort::Quick_Sort()
{
}
Quick_Sort::~Quick_Sort()
{
}
//对数组进行划分
template <class T>
int Quick_Sort::Partition(T *arry, const int start, const int finish)
{
unsigned TSize = sizeof(T);
int i = start - 1;
T key = arry[finish];
for (int j = start; j < finish; j++)
{
if (arry[j] <= key)
{
i++;
swap(arry + i, arry + j, TSize);
}
}
swap(arry + i + 1, arry + finish, TSize);
return i + 1;
}
//快排
template <class T>
void Quick_Sort::QuickSort(T *arry, const int start, const int finish)
{
if (start < finish)
{
unsigned pivot = Partition(arry, start, finish);
QuickSort(arry, start, pivot - 1);
QuickSort(arry, pivot + 1, finish);
}
}
//交换值
template <class T>
void Quick_Sort::swap (T* _target, T* _source, const unsigned size)
{
if (sizeof(T) < 128)
{
T temp;
temp = *_target;
*_target = *_source;
*_source = temp;
}
else
{
T* _temp = 0;
try
{
_temp = (T*)::operator new (size);
}
catch (bad_alloc& baRef)
{
cerr << "Error in Swap function: Can't allocate memory: " << baRef.what() << endl;
throw;
}
memcpy (_temp, _target, size);
memcpy (_target, _source, size);
memcpy (_source, _temp, size);
::operator delete (_temp);
_temp = 0;
}
}