Monday, December 15, 2014

Merge Sorted Array

Q:
Given two sorted integer arrays A and B, merge B into A as one sorted array.

T:
We can insert elements in B one by one. Keep an index pointing to the position where the current element in B should be inserted, and move the following elements in A one position afterwards.

A:


class Solution {
public:
    void merge(int A[], int m, int B[], int n) {
        int j=0;
        for(int i=0; i< n; i++) {
            while(j< m+i && A[j] < B[i]) {
                j++;
            }
            for(int k=m+i-1; k>=j; k--) {
                A[k+1] = A[k];
            }
            A[j] = B[i];
        }
    }
};

No comments:

Post a Comment