排序之二路歸併排序
阿新 • • 發佈:2018-12-09
分治思想
//歸併 void Merge(int R[],int left,int right) { int mid=(left+right)/2; int *p=(int *) malloc(sizeof(int)*(right-left+1)); int i=left,j=mid+1; int k=0; while(i<=mid&&j<=right){ if(R[i]>R[j]){ p[k++]=R[j++]; }else{ p[k++]=R[i++]; } } while(i<=mid) p[k++]=R[i++]; while(j<=right) p[k++]=R[j++]; k=0; while(left<=right){ R[left++]=p[k++]; } free(p); } //歸併排序 void MergeSort(int R[],int left,int right) { if(left<right){ int mid=(left+right)/2; MergeSort(R,left,mid); MergeSort(R,mid+1,right); Merge(R,left,right); } }