合并两个有序数组(48页)

剑指offer:

有两个排序数组A1和A2,内存在A1的末尾有足够多的剩余空间容纳A2,请实现一个函数,把A2中的所有数字插入到A1中并且所有的数字都是有序的。

思想: 同上一篇博文,从后往前遍历插入的思想

下面的代码没有经过测试,不知道对不对呢???????

void MergeArray(int a[], int b[], int a_len, int b_len) 
{   // 假设数组均按升序排列

	int total_len = a_len + b_len;
	int a_index = a_len - 1;
	int b_index = b_len - 1;
	int k = 1;
	while (a_index >= 0 && b_index >= 0)
	{
		if (a[a_index] > b[b_index])
		{
			a[total_len - k] = a[a_index];
			a[total_len - k - 1] = b[b_index];		
		}
		else
		{
			a[total_len - k] = b[b_index];
			a[total_len - k - 1] = a[a_index];
		}
		a_index--;
		b_index--;
		k += 2;
	}
	if (b_index != 0)
	{
		for (int j = 0; j <= b_index; j++)
			a[++a_index] = b[j];
	}
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值