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 andn respectively.
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 andn respectively.
void merge(int A[], int m, int B[], int n) {
int j = m+n-1, i = m-1,k;
if(n <= 0)return;
if(m<=0)
{
int k = 0;
while(k<n)
{
A[k] = B[k];
k++;
}
return;
}
while(i>=0)
{
A[j] = A[i];
i--;
j--;
}
i = j+1; j = 0, k = 0;
while(i<m+n && j<n)
{
if(A[i] <= B[j])
{
A[k++] = A[i++];
}
else A[k++] = B[j++];
}
while(j<n)
{
A[k++] = B[j++];
}
}
No comments:
Post a Comment