快速排序的递归和非递归实现方法
/*
快速排序的两种实现方法:
1、递归实现
2、非递归实现
*/
#include <iostream>
#include<stack>
using namespace std;
//以a[0]作为枢轴,将数组分开
int partition(int a[],int left,int right)
{
int temp=a[left];
while(left<right)
{
while(left<right&&a[right]>temp)
right--;
a[left]=a[right];
while(left<right&&a[left]<temp)
left++;
a[right]=a[left];
}
a[left]=temp;
return left;
}
//递归快排
void quicksort(int a[],int left,int right)
{
if(left<right)
{
int p=partition(a,left,right);
quicksort(a,left,p-1);
quicksort(a,p+1,right);
}
}
//非递归快排:用栈来存储两端的位置
void quickNonRecur(int a[],int left,int right)
{
stack<int>s;//存储两端的位置
if(left<right)
{
int pos=partition(a,left,right);//第一次切分
if(left<pos-1)//左边至少要有两个元素,若只有一个元素,则不用排了
{
s.push(left);
s.push(pos-1);
}
if(pos+1<right)//同理,右边也至少有两个元素。只有一个话的就自动有序了
{
s.push(pos+1);//成对入栈
s.push(right);
}
while(!s.empty())
{
int r=s.top();//每次必须是成对出栈
s.pop();
int l=s.top();
s.pop();
pos=partition(a,l,r);
if(pos-1>l)//不是1,而是L
{
s.push(l);
s.push(pos-1);
}
if(pos+1<r)
{
s.push(pos+1);
s.push(r);
}
}
}
}
void printArray(int a[],int n)
{
int i=0;
for(i=0;i<n;++i)
{
if(i==0)
printf("%d",a[i]);
else
printf(" %d",a[i]);
}
}
int main()
{
int a[]={12,3,24,-21,32,13,4,5,2,67,10};
int n=sizeof(a)/sizeof(a[0]);
//quicksort(a,0,n-1);
quickNonRecur(a,0,n-1);
printArray(a,n);
return 0;
}