快速排序----非递归
2013-05-23 15:15
218 查看
我们以前写快排都是写递归的。
今天突然想起来,若是让你改成非递归,该咋写呢。
在网上找了个。
运行结果是:
recurcive 4.932
none recurcive 7.959
请按任意键继续. . .
可以看到非递归的算法比递归实现还要慢。
下面解释为什么会这样。
递归算法使用的栈由程序自动产生,栈中包含:函数调用时的参数和函数中的局部变量。
如果局部变量很多或者函数内部又调用了其他函数,则栈会很大。
每次递归调用都要操作很大的栈,效率自然会下降。
而对于非递归算法,每次循环使用自己预先创建的栈,因此不管程序复杂度如何,都不会影响程序效率。对于上面的快速排序,由于局部变量只有一个mid,栈很小,所以效率并不比非递归实现的低。
#include<iostream> #include<vector> #include<stack> #include<stdlib.h> #include<algorithm> #include <time.h> using namespace std; 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; }
今天突然想起来,若是让你改成非递归,该咋写呢。
在网上找了个。
运行结果是:
recurcive 4.932
none recurcive 7.959
请按任意键继续. . .
可以看到非递归的算法比递归实现还要慢。
下面解释为什么会这样。
递归算法使用的栈由程序自动产生,栈中包含:函数调用时的参数和函数中的局部变量。
如果局部变量很多或者函数内部又调用了其他函数,则栈会很大。
每次递归调用都要操作很大的栈,效率自然会下降。
而对于非递归算法,每次循环使用自己预先创建的栈,因此不管程序复杂度如何,都不会影响程序效率。对于上面的快速排序,由于局部变量只有一个mid,栈很小,所以效率并不比非递归实现的低。
相关文章推荐
- 每天刷个算法题20160525:快速排序的递归转非递归解法
- 递归与分治策略-2.8快速排序
- 快速排序非递归c#实现
- 快速排序的非递归实现
- 快速排序【递归版】
- 快速排序的非递归实现
- 快速排序的递归和非递归解法
- Python递归实现快速排序
- javascript 递归之 快速排序
- 快速排序解剖(递归)
- 快速排序 递归与非递归
- 【数据结构笔记】7:非递归快速排序
- 快速排序 的原理及其java实现(递归与非递归)
- 快速排序的递归实现算法
- 快速排序之递归与非递归写法
- 快速排序的递归与非递归实现
- 快速排序Java源码(递归和非递归)
- 快速排序 递归和非递归
- 快速排序的非递归实现代码
- 快速排序的递归方式和非递归方式