Wednesday, 20 August 2014

Merge two sorted Arrays

Let 'a' and 'b' are two sorted arrays of size 'm' and 'n'. Merge arrays 'a' and 'b' to array 'c' .

public class MergeArrays {
    
    static int[] merge(int a[], int b[]){
        int m = a.length;
        int n = b.length;
        int aCount=0, bCount=0;
        int i=0;
        int c[] = new int[m+n];
        
        while(aCount<m && bCount<n){
            if(a[aCount] < b[bCount]){
                c[i] = a[aCount];
                aCount++;
            }
            else{
                c[i] = b[bCount];
                bCount++;
            }
            i++;
        }
        
        if(aCount==m){
           for(int j=bCount; j<n; j++)
               c[i++] = b[j];
        }
        else{
           for(int j=aCount; j<m; j++)
            c[i++] = a[j];
        }
        return c;
    }
    
    public static void main(String args[]){
        int a[] = {2,4,6,8,14};
        int b[] = {1,3,5,7,10,11,13};
        
        int c[] = merge(b,a);
        for(int i=0; i<c.length; i++){
            System.out.print(c[i] +" ");
        }
    }
}

Output
1 2 3 4 5 6 7 8 10 11 13 14


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment