int *mSort(int A[], const int al, const int ar, unsigned long* modifications) { if (ar > al) { int m = (ar + al) / 2; mSort(A, al, m, modifications); mSort(A, m + 1, ar, modifications); int *B = calloc(ar - al + 1, sizeof(int)); merge(A, al, m, A, m + 1, ar, B, modifications); for (int i = 0; i < ar - al + 1; i++) A[al + i] = B[i]; } return A; }
void mSort(int* sr, int* tr1, int s, int t) { if (s == t) tr1[s] = sr[s]; else { int* tr2 = malloc(100*sizeof(int)); int m = (s + t) / 2; mSort(sr, tr2, s, m); mSort(sr, tr2, m+1, t); Merge(tr1, tr2, s, m, t); free(tr2); } }
// 算法10.13 P284 // 将SR[s..t]归并排序为TR1[s..t] void mSort(RedType SR[],RedType TR1[],int s,int t){ int m; RedType TR2[MAXSIZE+1];//存储归并后的数组 if(s==t){ TR1[s] = SR[s]; //printf("(%d,%d)",s,TR1[s].key); //printf("%d,%d",SR[s].key,SR[s+1].key);exit(0); }else{ m = (s+t)/2;//将SR[s..t]平分为SR[s..m]和SR[m+1..t] mSort(SR,TR2,s,m);//递归地将SR[s..m]归并为有序的TR2[s..m] mSort(SR,TR2,m+1,t);//递归地将SR[m+1..t]归并为有序的TR2[m+1..t] //printf("%d,%d,%d",s,m,t);exit(0); merge(TR2,TR1,s,m,t);//将TR2[s..m]和TR2[m+1..t]归并到TR1[s..t] } }
void mSort(void **base,int length,CompareFunc compare){ int mid,i; void **left,**right; mid = length/2; left = malloc((mid+1)*sizeof(void*)); right = malloc((mid+1)*sizeof(void*)); if(length == 1) return; for(i=0;i<mid;i++) left[i] = base[i]; for(i=mid;i<length;i++) right[i-mid] = base[i]; mSort(left,mid,compare); mSort(right,length-mid,compare); merge(left,right,mid,length-mid,base,compare); free(left); free(right); };
int main() { int i; fscanf(stdin, "%d", &i); int* array = (int *)malloc(sizeof(int) * i); int j; for (j = 0; j < i; j++) { fscanf(stdin, "%d", &array[j]); } mSort(array, 0, i - 1); return 0; }
int main() { int fLines, start =2, i; char *fName = "worldcitiespoppartial.txt"; float **fpArray; int childpid, fds[2]; fpArray = fileInput(fName, &fLines); printf("Before it forks\n"); pipe(fds); childpid = fork(); if (childpid==0){ printf("This is a child Process\n"); fpArray = iSort(fpArray, (fLines/2), start); write(fds[1], fpArray, sizeof(long int)*3*fLines/2 ); } else { printf("This is a parent Process\n"); wait(NULL); read(fds[0], fpArray, sizeof(long int)*3*fLines/2); fpArray = iSort(fpArray, (fLines), (fLines/2)); fpArray = mSort(fpArray, fLines); for(i=1;i<fLines; i++){ printf("%.f %f %f\n", fpArray[i][0], fpArray[i][1], fpArray[i][2]); } } return(0); }
int* _mergesort (int array[], const int size, unsigned long* modifications) { return mSort(array, 0, size - 1, modifications); }
// 算法10.14 P284 // 对顺序表L作规定排序 void mergeSort(SqList *L){ mSort(L->r,L->r,1,L->length); }
void mergeSort(int* l, int length) { mSort(l, l, 0, length); }