Rotate your phone or change to desktop for better experience

Rotate your phone or change to desktop for better experience

merging two sorted arrays || JAVA

 //merging two sorted arrays


public class Main{

    

    public void merge(int A[],int B[], int C[])

    {

        int m,n;// m = length of Array A and n = Length of array @Before

        m = A.length;

        n=B.length;

        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++];

        }

        for(; i < m ; i++)

        C[k++]=A[i];

        for (; j< n ;j++)

        C[k++]=B[j];

        //while(i<)

    }

    

    public void display(int C[])

    {

        for(int i= 0 ; i < C.length;i++)

        System.out.println(C[i]);

    }

    

    public static void main(String[] args)

    {

        int [] A= new int[]{1,2,3,4};

        int [] B = new int[] {5,6,7,8};

        

        int [] C = new int[A.length+B.length];

        Main obj = new Main();

        obj.merge(A,B,C);

        obj.display(C);

        

    }

}


Post a Comment

0 Comments