排序思想:将含有n个记录的序列,看成n个有序子序列,每个子序列长度为1,如何两两归并,得到[n/2]([x]表示不小于x的最小整数)个长度2或1的有序子序列;
再两两合并,如此重复,最后得到一个长度为n的有序序列为止。
递归方法:
void MergeSort(SqList *L) { MSort(L->r,1,L->length); } void MSort(int arr[],int low,int high) { int mid; if(low<high){ mid =(low + high)/2; MSort(arr,low,mid); MSort(arr,mid+1,high); Merge(arr,low,mid,high); } } void Merge(int arr[],int low,int mid ,int high) { int i=low,j=mid+1,k=0; int *temp=(int *)malloc((high-low+1)*sizeof(int)); while(i<=mid&&j<=high) { if(arr[i]<=arr[j]) temp[k++]=arr[i++]; else temp[k++]=arr[j++]; } while(i<=mid) temp[k++]=arr[i++]; while(j<=high) temp[k++]=arr[j++]; for(i=low,k=0;i<=high;i++,k++) arr[i]=temp[k]; free(temp); }
非递归方法:
void MergeSort2(SqList *L) { int size=1,low,mid,high,n; n = L->length; while(size <= n){ low = 1; while(low+size <= n){ mid = low + size -1; high = mid + size; if(high>n) high = n; Merge(L->r,low,mid,high); low=high+1; } size*=2;/* 扩大范围 */ } }