已知快速排序的部分代码如下,勿改动,请利用栈实现快速排序非递归函数:void QuickSort(); //quickSort
#include<iostream>
using namespace std;
const int MaxSize=100;
class List
{
private:
int r[MaxSize+1];
int n;
public:
List(){n=0;} //empty list
void InsertR(int k) //表尾插入
{ r[++n]=k;}
void Display(); //display
void QuickSort(); //quickSort
};
void List::Display()
{
for(int i=1;i<=n;i++)
cout<<r[i]<<" ";
cout<<"\n";
}
int main()
{
List L;
while(1)
{
int k;
cin>>k;
if(!k) break;
L.InsertR(k);
}
L.Display();
L.QuickSort();
L.Display();
return 0;
}
Input
Output
Sample Input
12 21 32 2 4 24 21 432 23 9 0
Sample Output
12 21 32 2 4 24 21 432 23 9
2 4 9 12 21 21 23 24 32 432
//已知快速排序的部分代码如下,勿改动,请利用栈实现快速排序非递归函数:void QuickSort(); //quickSort
#include<iostream>
using namespace std;
#include<stack>
const int MaxSize=100;
class List
{
private:
int r[MaxSize+1];
int n;
public:
List(){n=0;} //empty list
void InsertR(int k) //表尾插入
{ r[++n]=k;}
void Display(); //display
void QuickSort(); //quickSort
int position(int first,int end);
};
int List::position(int first,int end)
{
int temp;
temp=r[first];
while(first<end)
{
while(first<end&&r[end]>=temp)
--end;
r[first]=r[end];
while(first<end&&r[first]<=temp)
++first;
r[end]=r[first];
}
r[first]=temp;
return first;
}
void List::Display()
{
for(int i=1;i<=n;i++)
cout<<r[i]<<" ";
cout<<"\n";
}
void List::QuickSort() //quickSort
{
stack <int> s;
s.push(n);
s.push(1);
while(!s.empty())
{
int i=s.top();
s.pop();
int j=s.top();
s.pop();
int p=position(i,j);
if(i<p-1)
{
s.push(p-1);
s.push(i);
}
if(j>p+1)
{
s.push(j);
s.push(p+1);
}
}
}
int main()
{
List L;
while(1)
{
int k;
cin>>k;
if(!k) break;
L.InsertR(k);
}
L.Display();
L.QuickSort();
L.Display();
return 0;
}