给定两个已经排序的数组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.