归并排序

二路归并排序

//二路归并排序
//分治法
//自底向上的二路归并排序算法
#include
#include
void disp(int a[],int n){
    int i;
    for(i=0;i 
 

  三路归并排序

//三路归并排序
void merge3(int a[],int l,int s1,int s2,int r){
	int i,j,k,h,*ta;
	i = l;
	j = s1+1;
	h = 0;
	ta = (int *)malloc((r-l+1)*sizeof(int));
	while(i<=s1 && j<=s2){	//将a[l..s1]和a[s1+1..s2]合并排序
 		if(a[i] <= a[j])	
			ta[h++] = a[i++];
		else
			ta[h++] = a[j++];	
	} 
	while(i <= s1)
		ta[h++] = a[i++];
	while(j <= s2)
		ta[h++] = a[j++];
	//将前两段的合并结果再和第三段合并
	for(k = 0;k < h;k++)
		a[l+k] = ta[k];
	i = l;
	j = s2+1;
	h = 0;
	while(i<=s2 && j<= r){
		if(a[i] <= a[j])	
			ta[h++] = a[i++];
		else
			ta[h++] = a[j++];	
	} 
	while(i <= s2)
		ta[h++] = a[i++];
	while(j <= r)
		ta[h++] = a[j++];
	for(k = 0;k < h;k++)
		a[l+k] = ta[k];
	free(ta);
}

  

你可能感兴趣的:(归并排序)