合并两个已经排序的数组

给定两个已经排序的数组A和B,A有足够大的空间去容纳B。

从数组A和B的尾部遍历比较元素,大的放在数组A的后面。最后如果B中还有元素,将其加入A中。

注意:不必在B中的元素遍历完后再次遍历A中的元素,因为他们已经在A中了。

You are given two sorted arrays, A and B, and A has a large enough buffer at the

end to hold B. Write a method to merge B into A in sorted order. 
SOLUTION
/* Input: a[], b[], n (number of elements in a) and
* m (number of elements in b)
int k = m + n - 1; // Index of last location of array b
int i = n - 1; // Index of last element in array b
int j = m - 1; // Index of last element in array a
// Start comparing from the last element and merge a and b
while (i >= 0 && j >= 0) {
	if (a[i] > b[j]) {
		a[k--] = a[i--];
	} else {
		a[k--] = b[j--];
	}
}
while (j >= 0) {
	a[k--] = b[j--];
}


Note: You don’t need to copy contents of a after running out of b’s. They are
already in place.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值