Mergesort
来源:互联网 发布:阿里云 ssh账号密码 编辑:程序博客网 时间:2024/05/18 02:39
1 /* 2 mergesort 3 */ 4 5 #include<stdio.h> 6 #include<stdlib.h> 7 /* Lpos = start of left half, Rpos = start of right half */ 8 //void Merge(ElementType A[]. ElementType TmpArray[], int Lpos, int Rpos, int RightEnd) 9 void Merge(int A[], int TmpArray[], int Lpos, int Rpos, int RightEnd) 10 { 11 int i, LeftEnd, NumElements, TmpPos; 12 13 LeftEnd = Rpos - 1; 14 TmpPos = Lpos; 15 NumElements = RightEnd - Lpos + 1; 16 17 /* main loop */ 18 while(Lpos <= LeftEnd && Rpos <= RightEnd) 19 if(A[Lpos] <= A[Rpos]) 20 TmpArray[TmpPos++] = A[Lpos++]; 21 else 22 TmpArray[TmpPos++] = A[Rpos++]; 23 24 while(Lpos <= LeftEnd) /* Copy rest of first half */ 25 TmpArray[TmpPos++] = A[Lpos++]; 26 while(Rpos <= RightEnd) /* Copy rest of second half */ 27 TmpArray[TmpPos++] = A[Rpos++]; 28 29 /* Copy TmpArray back */ 30 for(i = 0; i < NumElements; i++, RightEnd--) 31 A[RightEnd] = TmpArray[RightEnd]; 32 } 33 34 //void MSort(ElementType A[], ElementType TmpArray[], int Left, int Right) 35 void MSort(int A[], int TmpArray[], int Left, int Right) 36 { 37 int Center; 38 39 if(Left < Right){ 40 Center = (Left + Right) / 2; 41 MSort(A, TmpArray, Left, Center); 42 MSort(A, TmpArray, Center + 1, Right); 43 Merge(A, TmpArray, Left, Center + 1, Right); 44 } 45 } 46 47 //void Mergesort(ElementType A[], int N) 48 void Mergesort(int A[], int N) 49 { 50 //ElementType *TmpArray; 51 int *TmpArray; 52 53 TmpArray = malloc(N * sizeof(int*)); 54 if(TmpArray != NULL){ 55 MSort(A, TmpArray, 0, N - 1); 56 free(TmpArray); 57 } 58 else 59 printf("No space for tmp array!!!\n"); 60 } 61 62 int main() 63 { 64 int array[] = {4,1,23,76,55,13,14,2}; 65 int num, i; 66 num = sizeof(array) / sizeof(int); 67 Mergesort(array, num); 68 for(i = 0; i < num; i++) 69 printf("array[%d] = %d\n", i, array[i]); 70 return 0; 71 }