Merge Sorted Array

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

Notice

You may assume that A has enough space (size that is greater or equal tom+n) to hold additional elements from B. The number of elements initialized in A and B are _m _and _n _respectively.

Example

A =[1, 2, 3, empty, empty], B =[4, 5]

After merge, A will be filled as[1, 2, 3, 4, 5]

Solution: Merge from end.

public void mergeSortedArray(int[] A, int m, int[] B, int n) {
    if(A == null || A.length == 0) {
        return ;
    }
    while(m > 0 && n > 0) {
        if(A[m - 1] > B[n - 1]) {
            A[m + n - 1] = A[m - 1];
            m--;
        }    
        else {
            A[m + n - 1] = B[n - 1];
            n--;
        }
    }
    while(n > 0) {
        A[m + n - 1] = B[n - 1];
        n--;
    }
}

results matching ""

    No results matching ""