# Merge Two Sorted Array

``````给出A=[1,2,3,4]，B=[2,4,5,6]，返回 [1,2,2,3,4,4,5,6]
``````

``````你能否优化你的算法，如果其中一个数组很大而另一个数组很小？
``````

## Coding

``````# python
class Solution:
#@param A and B: sorted integer array A and B.
#@return: A new sorted integer array
def mergeSortedArray(self, A, B):
ai = 0
bi = 0
c = []
for i in range(len(A)+len(B)):
if ai < len(A) and bi < len(B):
if A[ai] < B[bi]:
c.append(A[ai])
ai = ai + 1
else:
c.append(B[bi])
bi = bi + 1
elif ai < len(A) and bi >= len(B):
c.append(A[ai])
ai = ai + 1
elif ai >= len(A) and bi < len(B):
c.append(B[bi])
bi = bi + 1
return c
``````
``````// java
class Solution {
/**
* @param A: sorted integer array A which has m elements,
*           but size of A is m+n
* @param B: sorted integer array B which has n elements
* @return: void
*/
public void mergeSortedArray(int[] A, int m, int[] B, int n) {
int i = m-1, j = n-1, index = m + n - 1;
while (i >= 0 && j >= 0) {
if (A[i] > B[j]) {
A[index--] = A[i--];
} else {
A[index--] = B[j--];
}
}
while (i >= 0) {
A[index--] = A[i--];
}
while (j >= 0) {
A[index--] = B[j--];
}
}
}
``````