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.
-
void merge(int A[], int m, int B[], int n) {
-
int i=m-1;
-
int j=n-1;
-
int k=m+n-1;
-
while(k>=0)
-
{
-
if(i==-1)
-
{
-
A[k--]=B[j--];
-
}
-
else if(j==-1)
-
{
-
A[k--]=A[i--];
-
}
-
else
-
{
-
if(A[i]>B[j])
-
A[k--]=A[i--];
-
else
-
A[k--]=B[j--];
-
}
-
}
-
}
-
void merge(int A[], int m, int B[], int n)
-
{//递归版本
-
int k=m+n-1;
if(k>=0)
{
if(m==0)
A[k]=B[--n];
else if(n==0)
A[k]=A[--m];
else
{
if(A[m-1]>B[n-1])
A[k]=A[--m];
else
A[k]=B[--n];
}
merge(A,m,B,n);
}
}
阅读(1642) | 评论(0) | 转发(0) |