1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| #include<stdlib.h> #include<stdio.h>
void Merge_sort(int *Data,int N); void Merge( int Data[], int TmpData[], int L, int R, int RightEnd ); void Msort(int Data[], int TmpData[], int N, int length); int main() { int i,N,*Data; scanf("%d\n",&N); Data = (int*)malloc(N*sizeof(int)); for(i = 0;i < N;i++) scanf("%d ",&Data[i]); Merge_sort(Data,N); for(i = 0;i < N-1; i++) printf("%d ",Data[i]); printf("%d\n",Data[N-1]); }
void Merge_sort(int *Data,int N) { int *TmpData,length; length = 1; TmpData = (int*)malloc(N * sizeof(int)); while(length < N){ Msort( Data, TmpData, N, length ); length *= 2; Msort( TmpData, Data, N, length ); length *= 2; } free( TmpData ); } void Msort(int Data[], int TmpData[], int N, int length) { int i,j; for( i = 0;i < N - 2*length; i+=2*length) Merge(Data, TmpData, i, i+length, i+2*length-1 ); if(i + length < N) Merge(Data, TmpData, i, i+length, N-1); else for(j = i;j < N;j++)TmpData[j] = Data[j]; }
void Merge( int Data[], int TmpData[], int L, int R, int RightEnd ) { int LeftEnd, NumElements, Tmp; NumElements = RightEnd - L + 1; LeftEnd = R-1; Tmp = L; while(L <= LeftEnd && R <= RightEnd) { if(Data[L] > Data[R]) TmpData[Tmp++] = Data[R++]; else TmpData[Tmp++] = Data[L++]; } while( L <= LeftEnd ) TmpData[Tmp++] = Data[L++]; while( R <= RightEnd ) TmpData[Tmp++] = Data[R++]; }
|