快速排序的递归和非递归实现
来源:互联网 发布:unity3d汉化版下载 编辑:程序博客网 时间:2024/06/03 09:25
#include<iostream>#include<vector>#include<stack>#include<cstdlib>#include<algorithm>using namespace std; /**把数组分为两部分,轴pivot左边的部分都小于轴右边的部分**/template <typename Comparable>int partition(vector<Comparable> &vec,int low,int high){ Comparable pivot=vec[low]; //任选元素作为轴,这里选首元素 while(low<high){ while(low<high && vec[high]>=pivot) high--; vec[low]=vec[high]; while(low<high && vec[low]<=pivot) low++; vec[high]=vec[low]; } //此时low==high vec[low]=pivot; return low;} /**使用递归快速排序**/template<typename Comparable>void quicksort1(vector<Comparable> &vec,int low,int high){ if(low<high){ int mid=partition(vec,low,high); quicksort1(vec,low,mid-1); quicksort1(vec,mid+1,high); }} /**使用栈的非递归快速排序**/template<typename Comparable>void quicksort2(vector<Comparable> &vec,int low,int high){ stack<int> st; if(low<high){ int mid=partition(vec,low,high); if(low<mid-1){ st.push(low); st.push(mid-1); } if(mid+1<high){ st.push(mid+1); st.push(high); } //其实就是用栈保存每一个待排序子串的首尾元素下标,下一次while循环时取出这个范围,对这段子序列进行partition操作 while(!st.empty()){ int q=st.top(); st.pop(); int p=st.top(); st.pop(); mid=partition(vec,p,q); if(p<mid-1){ st.push(p); st.push(mid-1); } if(mid+1<q){ st.push(mid+1); st.push(q); } } }} int main(){ int len=1000000; vector<int> vec; for(int i=0;i<len;i++) vec.push_back(rand()); clock_t t1=clock(); quicksort1(vec,0,len-1); clock_t t2=clock(); cout<<"recurcive "<<1.0*(t2-t1)/CLOCKS_PER_SEC<<endl; //重新打乱顺序 random_shuffle(vec.begin(),vec.end()); t1=clock(); quicksort2(vec,0,len-1); t2=clock(); cout<<"none recurcive "<<1.0*(t2-t1)/CLOCKS_PER_SEC<<endl; return 0;}
0 0
- 快速排序。冒泡排序递归和非递归的实现
- 快速排序的递归和非递归的实现
- 快速排序的递归和非递归实现
- 快速排序的递归和非递归实现
- 快速排序的递归和非递归实现
- 快速排序-递归和非递归的实现
- 快速排序的递归和非递归实现
- 快速排序的递归和非递归实现
- 快速排序的递归和非递归实现方法
- 快速排序的递归和非递归实现
- 快速排序的递归和非递归实现
- 快速排序的递归和非递归实现
- 快速排序的递归和非递归实现
- 快速排序、冒泡排序、堆排序、shell排序的递归和非递归实现
- 快速排序算法递归和非递归实现 [# 29]
- Java 实现快速排序 递归和非递归
- Java实现快速排序递归和非递归
- 快速排序的非递归实现
- Windows分页管理机制的学习(一)实践1
- HTML中的链接到另外一个页面的标签<a>的用法与规则
- 设计模式学习之备忘录模式(Memento,行为型模式)(19)
- 数据结构之插入排序之希尔排序(缩小增量排序)—参考整理严蔚敏数据结构
- c#使用数组实现二叉查找树
- 快速排序的递归和非递归实现
- 转:徐汉彬:亿级Web系统搭建——单机到分布式集群
- OO设计原则SOLID之浅分析
- import static静态导入
- Responder一点也不神秘————iOS用户响应者链完全剖析
- VC Picture控件的使用
- objective-c-UI控件之-UITextField-placeholder
- 《大教堂与集市》阅读笔记
- 设计模式学习之备忘录模式(Memento,行为型模式)(19)