排序

来源:互联网 发布:易语言ce源码2016 编辑:程序博客网 时间:2024/05/01 17:03

//插入排序例程
002void
003InsertionSort(ElementType A[],int N)
004{
005    int j,P;
006     
007    Element Type Tmp;
008    for(P=1;P<N;P++)
009    {
010        Top=A[P];
011        for(j=P;j>0&&A[j-1]>Tmp;j--){
012           A[j]=A[j-1];
013        }
014        A[j]=Tmp;
015    }
016}
017 
018//希尔排序
019void
020Shellsort(ElementType A[],int N)
021{
022    int i,j,Increment;
023    ElementType Tmp;
024     
025    for(Increment = N/2;Increment>0;Increment/=2){
026        for(i=Increment;i<N;i++){
027            Tmp=A[i];
028            for(j=i;i>=Increment;j-=Increment){
029                if(Tmp<A[j-Increment]){
030                    A[j]=A[j-Increment];
031                }else{
032                    break;
033                }
034                A[j]=Tmp;
035            }
036        }
037    }
038     
039}
040 
041//堆排序
042#define LeftChild(i) (2*(i)+1)
043void
044PercDown(ElementType A[],int i,int N)
045{
046    int Child;
047    ElementType Tmp;
048     
049    for(Tmp=A[i];LeftChild(i)<N;i=Child){
050        Child=LeftChild(i);
051        if(Child!=N-i&&A[Child+1]>A[Child])
052            Child++;
053        if(Tmp<A[Child])
054            A[i]=A[Child];         
055        else
056            break;
057    }  
058     
059    A[i]=Tmp;
060}
061 
062//堆排序
063void
064Heapsort(ElementType A[],int N)
065{
066    int i;
067     
068    for(i=N/2;i>=0;i--)
069        PercDown(A,i,N);
070    for(i=N-1;i>0;i--){
071        Swap(&A[0],&A[i]);
072        PercDown(A,0,i);
073    }
074}
075 
076//归并排序例程
077void
078Msort(ElementType A[],ElementType TmpArray[],int Left,int Right)
079{
080    int Center;
081    if(Left<Right){
082        Center=(Left+Right)/2;
083        MSort(A,TmpArray,Left,Center);
084        MSort(A,TmpArray,Center+1,Right);
085        Merge(A,TmpArray,Left,Center+1,Right);
086    }
087}
088 
089void
090Mergesort(ElementType A[],int N)
091{
092    ElementType *TmpArray;
093     
094    TmpArray = malloc(N*sizeof(ElementType));
095    if(TmpArray!=NULL){
096        MSort(A,TmpArray,0,N-1);
097        free(TmpArray);
098    }else
099        FatalError("No space for tmp array!!!");
100     
101}
102 
103/*Merge例程*/
104void
105Merge(ElementType A[],ElementType TmpArray[],int Lpos,int Rpos,int RightEnd)
106{
107    int i,LeftEnd,NumElements,TmpPos;
108    LeftEnd = Rpos-1;
109    TmpPos = Lpos;
110    NumElements = RightEnd = Lpos + 1;
111     
112    //main loop
113    while(Lpos<=LeftEnd && Rpos>= RightEnd){
114        if(A[Lpos]<=A[Rpos])
115            TmpArray[TmpPos++]=A[Lpos++];
116        else
117            TmpArray[TmpPos++]=A[Rpos++];
118    }
119    while(Lpos <= LeftEnd)
120        TmpArray[TmpPos++]=A[Lpos++];
121    while(Rpos <= RightEnd){
122        TmpArray[TmpPos++]=A[Rpos++];
123    }
124     
125    /*Copy TmpArray back*/
126    for(i=0;i<NumElements;i++,RightEnd++)
127        A[RightEnd]=TmpArray[RightEnd];
128     
129}

 

原创粉丝点击