快排的非递归实现

#include<iostream>

#include<vector>

#include<stack>

using namespace std;

vector<int>a;

void input()

{

//实现数组元素的初始化

freopen("test.txt","r",stdin);

intc,i,n;

cin>>n;

for(i=0;i<n;i++)

{

cin>>c;

a.push_back(c);

}

}

void output()

{

//输出数组中的元素;

inti;

for(i=0;i<a.size();i++)

cout<<a[i]<<" ";

cout<<endl;

}

int partition(intlow,int high)

{

//在low和high子间元素,实现a[low]之前的元素都小于a[low],

//a[low]之后的元素都大于a[low];

inttemp=a[low];

while(low<high)

{

while(low<high && a[high]>=temp)

high--;

a[low]=a[high];

while(low<high && a[low]<=temp)

low++;

a[high]=a[low];

}

a[low]=temp;

return low;

}

void qSort()

{

stack<int>s;

//用栈s保存要排序的元素的上界位置high和下界位置low,

//每轮快排结束后并得到中轴元素的位置pivotloc,则然后将

//low和pivotloc-1压栈,再将pivotloc+1和high压栈,使得下次分别对

//low到pivotloc-1之间的元素快排,和对pivotloc+1到high之间的元素实现快排;

//即可达到对整个数组的排序;

intlow=0,high=a.size()-1,pivotloc;

s.push(low);

s.push(high);

while(!s.empty())

{

high=s.top();

s.pop();

low=s.top();

s.pop();

if(low<high)

{

pivotloc=partition(low,high);

//cout<<"该轮结束后的元素为:";

//output();

s.push(pivotloc+1);

s.push(high);//将pivotloc+1和high压栈,使得下次将pivotloc+1到high之间的元素排序;

s.push(low);

s.push(pivotloc-1);//将low和pivotloc-1压栈,使得下次将low到pivotloc-1之间的元素排序;

}

}

}

int main()

{

input();

cout<<"排序前的元素为:";

output();

qSort();

cout<<"排序后的元素为:";

output();

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值