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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
Solution:
void merge(int A[], int m, int B[], int n) {
int pos = m+n-1;
m = m-1;
n = n-1;
while(n>=0&&m>=0)
{
if(A[m]>B[n])
{
A[pos] = A[m];
m--;
}
else
{
A[pos] = B[n];
n--;
}
pos--;
}
if(n>=0)
{
while(n>=0)
{
A[pos] = B[n];
pos--;
n--;
}
}
}
Note:
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
Solution:
void merge(int A[], int m, int B[], int n) {
int pos = m+n-1;
m = m-1;
n = n-1;
while(n>=0&&m>=0)
{
if(A[m]>B[n])
{
A[pos] = A[m];
m--;
}
else
{
A[pos] = B[n];
n--;
}
pos--;
}
if(n>=0)
{
while(n>=0)
{
A[pos] = B[n];
pos--;
n--;
}
}
}
No comments:
Post a Comment