我们有一个大小为m+n的数组,其中m个元素以排序顺序存在,并且第二个大小为n的数组也按排序顺序存在。我们希望将它们都排序并放置在第一个数组中,不应该给出第三个数组。
示例:
1, 3, 55, 66, 77, _, _, _
5, 9, 20
答案应该是: 1, 3, 5, 9, 20, 55, 66, 77
我们有一个大小为m+n的数组,其中m个元素以排序顺序存在,并且第二个大小为n的数组也按排序顺序存在。我们希望将它们都排序并放置在第一个数组中,不应该给出第三个数组。
示例:
1, 3, 55, 66, 77, _, _, _
5, 9, 20
答案应该是: 1, 3, 5, 9, 20, 55, 66, 77
进行常规的归并排序,但是以相反的方式比较最大的数字,将(反转后的)结果存储到第一个数组的末尾向后倒序。这样,您合并的元素永远不会被覆盖(如果您花一点时间思考,就很容易看出这种方法的有效性)。
// merge the elements in B[] to A[], starting from the last one
void merge(int A[], int m, int B[], int n) {
// m-1 and n-1 represent the current element index in A[] and B[] respectively
while (n > 0) { // there are still elements in B[] not merged
if (m > 0 && A[m-1] > B[n-1]) { // current element in A[] > current element in B[]
A[m+n-1] = A[m-1]; // move current element of A[] to its right position
--m; // decrease current element index of A[]
}
else { // current element in A[] <= current element in B[]
A[m+n-1] = B[n-1]; // move current element in B[] to its right position
--n; // decrease current element index of B[]
}
}
}
将第一个数组的内容移动到第一个数组的末尾,使得空元素现在位于开头。然后像往常一样将两个序列合并到第一个数组中。