India’s Best Job Seekers and Training Platform Forums Java Problems set Let’s say you have two input arrays with…

Tagged: , ,

  • Let’s say you have two input arrays with…

     Akash  updated 10 months ago 2 Members · 1 Post
  • Akash 

    Administrator
    at

    Let’s say you have two input arrays with sorted elements. Find the union.
    a[] = {2, 10, 14, 19, 51, 71}
    b[] = {2, 9, 19, 40, 51}
    Union = {2, 9, 10, 14, 19, 40, 51}

  • Akash 

    Administrator
    at

    class Main

    {

    public static void main(String[] args)

    {

    int a[] = {2, 10, 14, 19, 51, 71};

    int b[] = {2, 9, 19, 40, 51} ;

    int union[]= getUnion(a,b);

    for(int i=0;i<union.length-1;i++)

    {

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

    }

    }

    private static int[] getUnion(int[] a, int[] b) {

    int u[] = new int[a.length+b.length];

    int i=0,j=0,k=0;

    boolean flag =true;

    while(flag){

    if(a[i] == b[j]){

    u[k] =b[j];

    k+=1;

    j+=1;

    i+=1;

    }

    else if(a[i]<b[j]){

    u[k]=a[i];

    k+=1;

    i+=1;

    }

    else{

    u[k]=b[j];

    k+=1;

    j+=1;

    }

    if(j==b.length){

    flag=false;

    }

    }

    return u;

    }

    }

Log in to reply.

Original Post
0 of 0 posts June 2018
Now
KodNest Training New Batch is starting on 21st September 2020. Attend one week free demo classes.Register Now

New Report

Close