QuickSort快速排序源码
QuickSort.h源码
#include "stdafx.h"
template<typename T> class QuickSort
{
private:
static bool Compare(T a, T b, bool useDesc)
{
return useDesc?(a >= b) : (a <= b);
}
static void InnerSort(T arr[], int start, int end, bool useDesc)
{
if(start >= end)
{
return;
}
T b = arr[start];
int l = start;
int r = end;
while(l<r)
{
while(l<r && Compare(b, arr[r],useDesc))
{
r--;
}
if(l < r)
{
arr[l++] = arr[r];
}
while(l<r && Compare(arr[l], b,useDesc))
{
l++;
}
if(l<r)
{
arr[r--] = arr[l];
}
}
arr[l] = b;
InnerSort(arr,start, l-1, useDesc);
InnerSort(arr,l+1,end,useDesc);
}
public:
static void Sort(T arr[], int len, bool useDesc=false)
{
InnerSort(arr,0,len-1,useDesc);
}
};
QuickSortTest.h源码
#include "stdafx.h"
#include "QuickSort.h"
#include <iostream>
using namespace std;
class QuickSortTest
{
public:
void DoTest()
{
float arr[10] = {3,3.3f, 1.2f, 6.2f, 4.2f, 0.3f, 5.1f, 8, 7, 2.3f};
QuickSort<float>::Sort(arr,10,true);
for(int i=0; i<10; i++)
{
cout<< arr[i] << " ";
}
cout <<endl;
}
};