归并排序

 

归并排序是分治思想,未排序的序列在序列单元为1的时候就是排序的了,然后再把每个排序的元素整合起来就是排序的序列了。

算法时间复杂度未nlg(n)

根据下面代码可以看到时间复杂度公式为:T(n)=2T(n/2)+O(n),进而可以得出nlog2(n)

归并排序是稳定的

#include "stdio.h"
#include "string.h"

int A_array[10];
int B_array[10];
int merge(int start_low,int start_high,int end_low,int end_high,int *array)
{
	int loop = start_low;
	int i=0;
	for(i=start_low;i<=start_high;i++)  //start
	{
		A_array[i] = array[i];  
	}  
	for(i=end_low;i<=end_high;i++)
	{
		B_array[i] = array[i];
	}

	for(;loop<=end_high;loop++)
	{
		if(( end_low> end_high) ||  ( (A_array[start_low]<B_array[end_low]) && (start_low <=start_high) ) )  //if前半部分的判断目的是:当B_array已经到尾之后,全部使用A_array的元素
		{
			array[loop] = A_array[start_low];
			start_low++;
		}
		else 
		{
			array[loop]=B_array[end_low];
			end_low++;
		}
	}
	return 0;
}

void display(int* array,int len)
{
	int i = 0;
	for(;i<len;i++)
	{
		printf("%d ",array[i]);
	}
	printf("\n");
}


int merge_sort(int start,int end, int *array)
{
	if(start<end)
	{
		int middle = (start+end)/2 ;
		merge_sort( start,middle,array );
		merge_sort( (middle + 1),end,array );
		merge(start,middle,middle+1,end,array);
	}
	return 0;
}

int main()
{
	memset(A_array,0,10);
	memset(B_array,0,10);
	int array[10] = {11,7,12,10,5,100,0,3,9,200};
	display(array,10);
	printf("start\n");
	merge_sort(0,9,array);
	printf("end\n");
	display(array,10);
	return 0;
}



 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值