归并排序

这个就开始考验脑袋了

下面说一下代码实现思路,不然很难下手

首先要想好合并和分治

先写好其中一项,比如这次我是先写合并,那么分治的时候就要将就着合并的参数进行编码

void merge_Sequnece(int a[], int first, int mid, int last, int temp[])
{
	int i = first, j = mid + 1;
	int m = mid, n = last;
	int k = 0;

	while (i <= m && j <= n)
	{
		if (a[i] <= a[j])
			temp[k++] = a[i++];
		else
			temp[k++] = a[j++];
	}

	while (i <= m)
		temp[k++] = a[i++];

	while (j <= n)
		temp[k++] = a[j++];

	for (i = 0; i < k; i++)
		a[first + i] = temp[i];
}
思路很简单,为了实现在O(2n)的空间条件下进行合并,我们申请了一个临时数组作为中间变量,在合并的时候才用堆叠合并

注意到为了使得思考清晰,用的是<=而非<

void Divide_Sequence(int *S,int first, int last, int *temp){

	if (first < last){
		int mid = (first + last) / 2;
		Divide_Sequence(S, first, mid, temp);
		Divide_Sequence(S, mid + 1, last, temp);
		merge_Sequnece(S, first, mid, last, temp);
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	int *temp = new int[6];
	int S[5] = { 31, 41, 59, 26, 41 };
	Divide_Sequence(S, 0, 4, temp);

	for (int i = 0; i < 5; i++){
		std::cout << S[i] << " ";
	}
	system("pause");
	delete []temp;
	return 0;
}

调用和分治


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值