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.
思路:该题较easy,归并排序中的合并步骤。
代码:
void merge(int A[], int m, int B[], int n) {
int indexOfInsert=m+n-1;
int indexOfA=m-1;
int indexOfB=n-1;
while(indexOfA>=0 && indexOfB>=0)
{
if(A[indexOfA]>=B[indexOfB])
{
A[indexOfInsert--]=A[indexOfA--];
}
else
{
A[indexOfInsert--]=B[indexOfB--];
}
}
if(indexOfB>=0)
{
while(indexOfB>=0)
{
A[indexOfInsert--]=B[indexOfB--];
}
}
}