快速排序的非递归主要使用栈来实现。
void QuickSortNonR(int* a,int left,int right)
{
stack<int> s;
s.push(right);
s.push(left);
while(!s.empty())
{
int begin = s.top();
s.pop();
int end = s.top();
s.pop();
int div = Partition2(a,begin,end);
//[begin,div-1]
if(begin < div-1)
{
s.push(div-1);
s.push(begin);
}
//[div+1,end]
if(div+1 < end)
{
s.push(end);
s.push(div+1);
}
}
}
void TestQuickNonR()
{
int a[] = {12,3,7,9,5,20,32,36,10};
QuickSortNonR(a,0,sizeof(a)/sizeof(a[0])-1);
PrintArray(a,sizeof(a)/sizeof(a[0]));
}
运行结果: