quick_sort.cpp
#include <iostream>
#include <vector>
#include <iterator>
#include <ctime>
#include <algorithm>
using namespace std;
namespace algo
{
/// 随机采样快排 平均效率O(nlgn)且常数因子很小 最坏效率O(n^2)
void QuickSort(vector<int> &toSort,int beginIndex,int endIndex)
{
if(beginIndex < endIndex)
{
int random_swap = (rand() % (endIndex - beginIndex + 1)) + beginIndex;
swap(toSort[random_swap],toSort[endIndex]);
int i = beginIndex;
for(int j=beginIndex;j!=endIndex;j++)
{
if(toSort[j] < toSort[endIndex])
{
swap(toSort[i],toSort[j]);
i++;
}
}
swap(toSort[i],toSort[endIndex]);
QuickSort(toSort,beginIndex,i-1);
QuickSort(toSort,i+1,endIndex);
}
}
}
测试代码:
#include <iostream>
#include <vector>
#include <ctime>
#include <iterator>
#include "quick_sort.cpp"
using namespace std;
int main()
{
cout << "快速排序" << endl;
vector<int> toSort;
for(int i=0;i<100;i++)
{
toSort.push_back(rand());
}
cout << "随机填充100个数:" << endl;
copy(toSort.begin(),toSort.end(),ostream_iterator<int>(cout,"\t"));
algo::QuickSort(toSort,0,toSort.size()-1);
cout << endl << "快排结果:" << endl;
copy(toSort.begin(),toSort.end(),ostream_iterator<int>(cout,"\t"));
return 0;
}
测试结果: