递归算法使用的栈由程序自动产生,栈中包含:函数调用时的参数和函数中的局部变量。如果局部变量很多或者函数内部又调用了其他函数,则栈会很大。每次递归调用都要操作很大的栈,效率自然会下降。
而对于非递归算法,每次循环使用自己预先创建的栈,因此不管程序复杂度如何,都不会影响程序效率。
void qsort2(int a[],int low ,int high)
{stack<int> st;
if (low<high)
int mid =partition(a,low,high);
if (low<mid-1){
st.push(low);
st.push(mid-1);
}
if (mid+1<high){
st.push(mid+1);
st.push(high);
}
while(!st.empty())
{
int q=st.top();
st.pop();
int p=st.top();
st.pop();
mid=partition(a,p,q);
if (p<mid){
st.push(p);
st.push(mid-1);
}
if (mid+1<q)
{
st.push(mid+1);
st.push(q);
}
}
}