您的位置:首页 > 其它

用非递归的方法实现快速排序

2010-12-25 22:55 204 查看
貌似现在接触到的快速排序都使用递归方法,无可厚非在这个算法中递归确实是很不错的方法。但是纠结的算法老师要让我们实现非递归的方法来实现快速排序。上过数据结构的应该都知道递归的方法在程序执行的时候其实是通过栈来实现递归的现场保护(不知道是不是应该这么说)。所以还是使用了栈来实现这个算法,45 行代码应该很好理解。

#include <iostream>
#include <stack>
using namespace std;
#define MAX_SIZE 8
int  Qsort(int *a,int low,int high){
int key=a[low];
while(low<high){
while(low<high&&a[high]>=key) high--;
a[low]=a[high];
while(low<high&&a[low]<=key) low++;
a[high]=a[low];
}
a[low]=key;
return low;
}
int main(){
int a[MAX_SIZE]={49,38,65,97,76,13,27,49};
int low=0;
int high=MAX_SIZE-1;
int num=Qsort(a,low,high);
stack<int> s;
s.push(low);
s.push(num-1);
s.push(num+1);
s.push(high);
while(!s.empty()){
high=s.top();
s.pop();
low=s.top();
s.pop();
if(low<high){
num=Qsort(a,low,high);
if(low<num-1){
s.push(low);
s.push(num-1);
}
if(num+1<high){
s.push(num+1);
s.push(high);
}
}
}
for(int i=0;i<MAX_SIZE;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: