使用非递归原因
因为当数据量非常大的时候,使用递归就会产生巨大的栈帧,就会造成栈溢出,所以我们来学习一下非递归是如何实现快排算法
实现方法
递归的算法主要是在划分子区间,如果要非递归实现快排,只要使用一个栈来保存区间就可以了。一般将递归程序改成非递归首先想到的就是使用栈,因为递归本身就是一个压栈的过程。
代码实现
int PartSort3(vector<int>& a,int begin,int end)
{
int cur=begin;
int key=a[end];
int prev=begin-1;
while(cur<end)
{
if(a[cur]<key)
{
prev++;
swap(a[prev],a[cur]);
}
cur++;
}
prev++;
swap(a[prev],a[end]);
return prev;
}
void QuickSort(vector<int>& a,int begin,int end)
{
stack<int> s;
s.push(begin);
s.push(end);
while(!s.empty())
{
int right=s.top();
s.pop();
int left=s.top();
s.pop();
int keyindex=PartSort3(a,left,right);
if(left<keyindex-1)
{
s.push(left);
s.push(keyindex-1);
}
if(keyindex+1<right)
{
s.push(keyindex+1);
s.push(right);
}
}
}
int main()
{
int n;
cin >> n;
vector<int> a;
while (n--)
{
int k;
cin >> k;
a.push_back(k);
}
QuickSort(a, 0,a.size()-1);
for (auto e : a)
{
cout << e << " ";
}
system("pause");
return 0;
}