排序的各种方法
给自己一点时间接受自己,爱自己,趁着下午茶的时间来学习图老师推荐的排序的各种方法,过去的都会过去,迎接崭新的开始,释放更美好的自己。
#include "stdio.h"
#include "malloc.h"
#include "conio.h"
#define maxsize 5
typedef strUCt{
int key;
}redtype;
typedef struct{
redtype *r;
int length;
}sqlist;
;
;
;
void shellsort(sqlist l,int d)
{
int i,j;
d=l.length/2;
while(d0)
{
for(i=d+1;i=l.length;++i)
if(l.r[i].keyl.r[i-d].key)
{
l.r[0]=l.r[i];
for(j=i-d;j0&&l.r[0].keyl.r[j].key;j-=d)
l.r[j+d]=l.r[j];
l.r[j+d]=l.r[0];}
d=d/2;}
}
;
;
;
void quicksort(sqlist l,int low,int high)
{int i,j;
if(lowhigh)
{i=low;j=high;l.r[0]=l.r[i];
do
{
while(ij&&l.r[j].keyl.r[0].key)
--j;
if(ij)
{l.r[i]=l.r[j];++i;}
while(ij&&l.r[i].key=l.r[0].key)
++i;
if(ij){
l.r[j]=l.r[i];--j;
}
}while(i!=j);
l.r[i]=l.r[0];
quicksort(l,low,i-1);
quicksort(l,i+1,high);
}
}
;
;
;
void heapadjust(sqlist l,int s,int m)
{
int rc,j;
rc=l.r[s].key;
for(j=2*s;j=m;j*=2)
{
if(jm&&l.r[j].keyl.r[j+1].key)
j++;
if(rcl.r[j].key)
break;
l.r[s].key=l.r[j].key;
s=j;
}
l.r[s].key=rc;
}
;
;
;
void heapsort(sqlist l)
{
int i,t;
for(i=l.length/2;i0;i--)
heapadjust(l,i,l.length);
for(i=l.length;i1;i--)
{
t=l.r[1].key,l.r[1].key=l.r[i].key,l.r[i].key=t;
heapadjust(l,1,i-1);
}
}
;
;
;
void oesort(sqlist l,int n)
{
int t,i,change;
change=1;
while(change)
{
change=0;
for(i=1;in;i+=2)
if(l.r[i].keyl.r[i+1].key)
{
t=l.r[i].key,l.r[i].key=l.r[i+1].key,l.r[i+1].key=t;
change=1;
}
for(i=2;in;i+=2)
if(l.r[i].keyl.r[i+1].key)
{
t=l.r[i].key,l.r[i].key=l.r[i+1].key,l.r[i+1].key=t;
change=1;
}
}
}
;
;
;
main()
{
int i,j,low,high,a[maxsize+1];
char ch;
sqlist l;
clrscr();
l.r=(redtype *)malloc(maxsize*sizeof(int));
if(!l.r)
printf("overflow");
l.length=0;
printf("please input five elements:");
for(i=1;imaxsize+1;i++)
{
scanf("%d",&a[i]);
l.length++;
}
getchar();
do
{
for(j=1,i=1;jmaxsize+1;i++,j++)
l.r[i].key=a[j];
printf("Welcome to use PanWeiFeng's KeChenSheJi");
printf("s:shellsortq:quicksort");
printf("h:heapsorte:oesort");
printf("o:quit");
printf("please input the way:");
ch=getchar();
clrscr();
printf("the orignal array:");
for(i=1;imaxsize+1;i++)
printf("%d ",l.r[i].key);
printf("");
/*printf("please input the way:");
ch=getchar();*/
getchar();
switch(ch)
{
case 's':
shellsort(l,l.length);
printf("the odered arry:");
for(i=1;imaxsize+1;i++)
printf("%d ",l.r[i].key);
printf("");
break;
case 'q':
low=1;high=l.length;
quicksort(l,low,high);
printf("the odered arry:");
for(i=1;imaxsize+1;i++)
printf("%d ",l.r[i].key);
printf("");
break;
case 'h':
heapsort(l);
printf("the odered arry:");
for(i=1;imaxsize+1;i++)
printf("%d ",l.r[i].key);
printf("");
break;
case 'e':
oesort(l,l.length);
printf("the odered arry:");
for(i=1;imaxsize+1;i++)
printf("%d ",l.r[i].key);
printf("");
break;
case 'o':
exit(0);
default:
printf("error!write again!");
}
}while(1);
}
点这里下载