源码系列:快速排序
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; }
测试结果:
相关文章推荐
- 关于插入、合并、快速排序的源码
- 白话经典算法系列之六 快速排序 快速搞定
- 白话经典算法系列之六 快速排序 快速搞定
- 《大话数据结构》读书笔记之快速排序源码及其优化
- 数据结构排序系列详解之四 快速排序
- 快速排序源码(quick sort)
- 白话经典算法系列之六 快速排序 快速搞定
- 【转载】白话经典算法系列之六 快速排序 快速搞定
- 白话经典算法系列之六 快速排序 快速搞定
- 快速排序原地分区源码
- 白话经典算法系列之六 快速排序 快速搞定
- 内部排序系列 之 冒泡排序与快速排序
- 快速排序Java源码(递归和非递归)
- 白话经典算法系列之六 快速排序 快速搞定
- 白话经典算法系列之六 快速排序 快速搞定
- 快速排序(二) jdk源码中如何优化快速排序
- 【排序系列】快速排序java实现
- 快速排序源码
- 排序系列--快速排序
- 白话经典算法系列之六 快速排序 快速搞定