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
| #define ElemType int
int cmp(const void* e1,const void* e2){ return *(ElemType*)e1 - *(ElemType*)e2; } void merge(ElemType* A,ElemType* TempA,int l,int r,int REnd,int (*cmp)(const void* e1,const void* e2)){
int LEnd = r - 1; int n = REnd - l + 1; int subscript = l; while(l<=LEnd && r<=REnd) { if ( cmp(&A[l], &A[r])>0 ) TempA[subscript++] = A[r++]; else TempA[subscript++] = A[l++]; } while(r<=REnd) TempA[subscript++] = A[r++]; while(l<=LEnd) TempA[subscript++] = A[l++]; for (int i = 0; i < n; ++i,REnd--) A[REnd] = TempA[REnd]; } void merge_pass(ElemType* A,ElemType* TempA,int n,int length,int (*cmp)(const void* e1,const void* e2)){
int i; for ( i = 0; i <= n-2*length; i+=2*length) { merge(A,TempA,i,i+length,i+2*length-1,cmp); } if(i+length < n) merge(A,TempA,i,i+length,n-1,cmp); else for (int j = i; j < n; ++j) TempA[j] = A[j]; }
void mergesort(ElemType* A,int n,int (*cmp)(const void* e1,const void* e2)){ int length = 1; ElemType *TemA = (ElemType*)malloc((n)*sizeof (ElemType)); if(TemA){ while (length < n){ merge_pass(A,TemA,n,length,cmp); length <<= 1; merge_pass(TemA,A,n,length,cmp); length <<= 1; } free(TemA); }else perror("error: malloc fault"); }
|