Merge Sorted Array

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.

class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
         int * C = new int[m+n];
        int i = 0, j = 0, k = 0;
        while(i < m && j < n){
            if (A[i] < B[j]){
                C[k++] = A[i++];
            }else{
                C[k++] = B[j++];
            }
        }
        while(i < m){
            C[k++] = A[i++];
        }
        while(j < n){
            C[k++] = B[j++];
        }
        memcpy(A,C,sizeof(int)*(m+n));
        delete []C;               
    }
};

 

posted @ 2013-07-09 21:58  一只会思考的猪  阅读(139)  评论(0编辑  收藏  举报