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.
void merge(int A[], int m, int B[], int n) { int Aidx = m-1,Bidx = n-1; int Newidx = m+n-1; while (Aidx >= 0 && Bidx >= 0) { if (A[Aidx]>B[Bidx]){ A[Newidx] = A[Aidx]; Aidx--; } else{ A[Newidx] =B[Bidx]; Bidx--; } Newidx--; } if (Aidx >= 0){ for (int i = Aidx;i>=0;--i,--Newidx) A[Newidx] = A[i]; } else { for (int i = Bidx;i>=0;--i,--Newidx) A[Newidx] = B[i]; } }
原文:http://blog.csdn.net/li_chihang/article/details/44587281