Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
题目解析:
(1)基本的想法是从两个数组的末尾开始比较,将比较大,移动到A数组index处,index最大的时候为(m+n-1)。
#include <iostream>
using namespace std;
void merge(int A[], int m, int B[], int n) {
int index = m+n-1;
int i = m -1;
int j = n -1;
while(i>=0&&j>=0)
{
if(A[i]>B[j])
{
A[index] = A[i];
index--;
i--;
}else{
A[index] = B[j];
index--;
j--;
}
}
if(j>=0)
{
for(int k=0;k<=j;k++)
A[k] = B[k];
}
}
int main(void)
{
system("pause");
return 0;
}