【分享】我自编的C排序程序(第二版)
//------------------------------------------------// 这是自编排序代码 sorting 堪与 Shell 排序媲美
//------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <time.h>
typedef int Type;
#define NMAX 10000000
Type stack[NMAX];
#define SWAP(a,b) {Type t=a;a=b;b=t;}
void sorting(Type A[ ],int num)
{
if(num==2)
{
if(A[0]<A[1])SWAP(A[0],A[1]);
}
else if(num==3)
{
if(A[0]<A[1])SWAP(A[0],A[1]);
if(A[1]<A[2])SWAP(A[1],A[2]);
if(A[0]<A[1])SWAP(A[0],A[1]);
}
else
{
Type *p=stack,*boy,*girl;
int N1,N2,i,j;
N1 = num/2;
N2 = num - N1;
boy=A+0;
girl=A+N1;
sorting(boy ,N1); //递归
sorting(girl,N2); //递归
i=0;
if(boy[0]<girl[0])goto here;
do
{
for(i=1;i<N1;i++)if(boy[i]<girl[0])break;
memcpy(p,boy,i*sizeof(Type));
p+=i;boy+=i;N1-=i;
if(N1)goto here;
memcpy(p,girl,N2*sizeof(Type));
p+=N2;girl+=N2;N2=0;
goto outw;
here:
for(j=1;j<N2;j++)if(girl[j]<boy[0])break;
memcpy(p,girl,j*sizeof(Type));
p+=j;girl+=j;N2-=j;
}
while(N2>0);
memcpy(p,boy,N1*sizeof(Type));
p+=N1;boy+=N1;N1=0;
outw:
memcpy(A,stack,num*sizeof(Type));
}
}
void Shell(Type *ary,int num) //希尓排序
{
int i,j,dx=1;
for(dx=(int)(num/2.7); dx>=1; dx=(int)(dx/2.7))
for(i=dx; i<num; i++)
{ Type t=ary[i];
for(j=i; j>=dx && t>ary[j-dx]; j-=dx)
ary[j]=ary[j-dx];
ary[j]=t;
}
}
int main( void )
{
int i,t1,t2;
static Type ary[NMAX];
while(1)
{
printf("Random Seed: ");
scanf("%d",&i);srand(i);
for(i=0;i<NMAX;i++)
ary[i]=rand( )%900+100;
t1=clock( );
sorting( ary,NMAX );//俺的排序
//Shell( ary,NMAX );//希尓排序
t2=clock( );
for(i=0;i<NMAX;i+=100)printf("%d ",ary[i]);
printf("\n%d ms\n",(t2-t1));
}
return 0;
}