#include <iostream>
using namespace std;
#define MAXSIZE 20
typedef struct
{
int key;
char *otherinfo;
}ElemType;
typedef struct
{
ElemType *r;
int length;
}SqList;
int flag=1;
void Create_Sq(SqList &L)
{
int i,n;
cout<<"请输入数据个数,不超过"<<MAXSIZE<<"个。"<<endl;
cin>>n;
cout<<"请输入待排序的数据:\n";
while(n>MAXSIZE)
{
cout<<"个数超过上限,不能超过"<<MAXSIZE<<",请重新输入"<<endl;
cin>>n;
}
for(i=1;i<=n;i++)
{
cin>>L.r[i].key;
L.length++;
}
}
void show(SqList L)
{
int i;
for(i=1;i<=L.length;i++)
cout<<L.r[i].key<<" ";
//cout<<endl;
}
int Partition(SqList &L,int low,int high,int flag)
{ //对顺序表L中的子表r[low..high]进行一趟排序,返回枢轴位置
ElemType k=L.r[low];
while(low<high)
{
while(low<high&&L.r[high].key>=k.key)
high--;
if(low<high)
L.r[low++]=L.r[high];
while(low<high&&L.r[low].key<=k.key) //这个地方被坑了,符号注意下
low++;
if(low<high)
L.r[high--]=L.r[low];
}
L.r[low]=k;
cout<<"第 "<<flag<<" 趟排序 ";
show(L);
cout<<"中枢节点为:"<<L.r[low].key;
cout<<endl;
return low;
}//Partition
void QSort(SqList &L,int low,int high)
{ //调用前置初值:low=1; high=L.length;
//对顺序表L中的子序列L.r[low..high]做快速排序
int pivotloc;
if(low<high)
{ //长度大于1
pivotloc=Partition(L,low,high,flag++); //将L.r[low..high]一分为二,pivotloc是枢轴位置
QSort(L,low,pivotloc); //对左子表递归排序
QSort(L,pivotloc+1,high); //对右子表递归排序
}
} //QSort请补齐代码
void QuickSort(SqList &L)
{
//对顺序表L做快速排序
QSort(L,1,L.length);
} //QuickSort
void main()
{
SqList L;
L.r=new ElemType[MAXSIZE+1];
L.length=0;
Create_Sq(L);
QuickSort(L);
cout<<"排序后的结果为:"<<endl;
show(L);
}
快速排序
最新推荐文章于 2021-07-10 14:59:05 发布