#include<stdio.h>
#define MAXSIZE 20
typedef struct{
int key;
}redtype;
typedef struct{
redtype r[MAXSIZE+1];
int length;
}sqlist;
//堆排序
void heapadjust(sqlist &L,int s, int m){
redtype rc;
rc=L.r[s];
for(int j =2*s;j<=m;j*=2){
if(j<m&&L.r[j].key<L.r[j+1].key)
++j;
if(rc.key >=L.r[j].key)
break;
L.r[s]=L.r[j];
s=j;
}
L.r [s]=rc;
}
void creathep(sqlist &L){
int n=L.length;
for(int i=n/2;i>0;--i){
heapadjust(L,i,n);
}
}
void heapsort(sqlist &L){
creathep(L);
redtype x;
for(int i=L.length;i>1;--i){
x=L.r[1];
L.r[1] = L.r[i];
L.r[i] = x;
heapadjust(L,1,i-1);
}
}
//shell排序
void shellinsert(sqlist &L,int k){
int j;
for(int i=k+1;i<=L.length;++i)
if(L.r[i].key<L.r[i-k].key){
L.r[0]=L.r[i];
for(j=i-k;j>0 && L.r[0].key<L.r[j].key;j-=k)
L.r[j+k]=L.r[j];
L.r[j+k] = L.r[0];
}
}
void shellsort(sqlist &L,int dt[],int t){
for(int k =0;k<t;++k){
shellinsert(L,dt[k]);
}
}
//快速排序
int partition(sqlist &L,int low,int hight){
int pivo;
L.r[0] = L.r[low];
pivo = L.r[low].key;
while(low<hight){
while(low<hight&&L.r[hight].key>=pivo)
--hight;
L.r[low]=L.r[hight];
while(low<hight&&L.r[low].key<=pivo)
++low;
L.r[hight] = L.r[low];
}
L.r[low]=L.r[0];
return low;
}
void qsort(sqlist &L,int low,int hight){
int pivo;
if(low<hight){
pivo = partition(L,low,hight);
qsort(L,low,pivo-1);
qsort(L,pivo+1,hight);
}
}
void quicksort(sqlist &L){
qsort(L,1,L.length);
}
int main(){
sqlist a,b,c;
printf("请输入需要排序的数字的个数:\n");
scanf("%d",&a.length);
printf("请输入需排序的数字:\n");
for(int i=1;i<a.length+1;i++){
scanf("%d",&a.r[i].key);
}
c=b=a;
printf("\n******************************************\n");
heapsort(a);
printf("堆排序结果为:\n");
for(int i=1;i<a.length+1;i++){
printf("%d\t",a.r[i].key);
}
printf("\n******************************************\n");
int ww[3]={5,3,1};
shellsort(b,ww,3);
printf("shell排序结果为:\n");
for(int i=1;i<a.length+1;i++){
printf("%d\t",b.r[i].key);
}
printf("\n******************************************\n");
quicksort(c);
printf("快速排序结果为:\n");
for(int i=1;i<a.length+1;i++){
printf("%d\t",c.r[i].key);
}
printf("\n******************************************\n");
}
数据结构:排序(C语言)
最新推荐文章于 2022-10-04 19:20:43 发布