现在的位置: 首页 > 综合 > 正文

快速排序的非递归实现代码

2013年06月27日 ⁄ 综合 ⁄ 共 619字 ⁄ 字号 评论关闭

#include <iostream>
#include <stack>

using namespace std;
int partition(int * p,int a,int b);
void QuickSort(int * p,int size)
{

stack<int> s;
int low=0,high=size-1;
while(!s.empty()||low<high)
{
while(low<high)
{
int t=partition(p,low,high);
s.push(t);
high=t-1;
}
int t=s.top();
s.pop();
low=t+1;
if(s.empty())
high=size-1;
else
high=s.top()-1;
}
}
int partition(int * p,int a,int b)
{
int t=p[a];
int m=a,n=b;
while(m<n)
{
while(p[n]>=t&&m<n)
{
n--;
}
   p[m]=p[n];
while(p[m]<t&&m<n)
{
m++;
}
p[n]=p[m];
}
p[m]=t;
return m;

}
void main()
{
int size=0;
cin>>size;
int * p=new int[size];
for(int i=0;i!=size;++i)
{
cin>>p[i];
}
QuickSort(p,size);
for(int i=0;i!=size;++i)
cout<<p[i]<<" ";
::system("pause");
}

抱歉!评论已关闭.