您的位置:首页 > 其它

源码系列:快速排序

2014-12-18 22:04 337 查看
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;
}


测试结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: