您的位置:首页 > 理论基础 > 数据结构算法

归并排序(merge sort)

2014-09-11 19:21 274 查看
归并排序利用分治算法

1 divide:将数组平均分两部分(mergesort函数)

2 conquer:两部分数组分别排序(mergesort函数)

3.combine:将两部分按从小到大交替写入临时数组,最后复制到原数组(merge函数)

算法的接口驱动为mergedrive函数

注意:递归过程中,函数merge某一次可能只会用到tmp的一部分,所以i=lft而不是0,同样从tmp复制回a的时候也只是复制一部分,而不是全部复制

算法的复杂度

T(n) = 2T(n/2) + O(n)

      = O(nlogn)

void merge(int a[],int tmp[],int begin,int mid,int end){
int rth,lft,i,n;
rth = mid + 1;
lft = begin;
i = lft;
n = end - begin +1;
while(lft<=mid&&rth<=end){
if(a[lft]<a[rth])
tmp[i++] = a[lft++];
else tmp[i++] = a[rth++];
}
while(lft<=mid){
tmp[i++] = a[lft++];
}
while(rth<=end){
tmp[i++] = a[rth++];
}
for(i = 0;i<n;i++,end--)//将tmp的内容拷贝回去
a[end] = tmp[end];
}

void mergesort(int a[],int tmp[],int begin,int end){
int mid;
mid = (begin + end) / 2;
if(begin<end){
mergesort(a,tmp,begin,mid);
mergesort(a,tmp,mid+1,end);
merge(a,tmp,begin,mid,end);
}
}
void mergedrive(int a[],int n){
int *tmp;
int i;
tmp = (int *)malloc(sizeof(int)*n);
if(tmp!=NULL){
mergesort(a,tmp,0,n-1);
}
free(tmp);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息