Sunday, March 12, 2023

Mixing Two Ascending order Arrays into Third Array

 
A class Mixer has been defined to merge two sorted integer arrays in ascending order. Some of the member function and variables are as follows.

int arr[]: stores the elements in ascending order
int n=size of array

Mixer (int nn): constructor to assign n=nn;

void accept(): accepts elements in ascending order without any duplicate

Mixer mix(Mixer A): Merge current object array elements with parameterised object array into the array of a third object and returns the object

void display(): display array of all objects

Define main () method and create objects and invoke all methods


import java.util.*;
public class Mixer
{
int arr[];
int n;
Mixer(int nn)
{
     n=nn;
     arr=new int [n];
}
void accept()
{
   Scanner sc=new Scanner(System.in);
   for(int i=0;i<n;i++)
   {
       System.out.print("\nEnter Value:");
       arr[i]=sc.nextInt();
   }    
}
Mixer mix(Mixer A)
{
     int x=n+A.n;
     Mixer ob=new Mixer(x);
     int i,j,k;
     i=0;
     j=0;
     k=0;
     while(i<n && j<A.n)
     {
         if(arr[i]<=A.arr[j])
         {
             ob.arr[k++]=arr[i];
             i++;
         }
         else
         {
           ob.arr[k++]=A.arr[j];
             j++;  
             
         }
         if(i==n|| j==A.n)
         break;
     }
         if(i==n)
     {
         for(;k<x;k++)
         {
              ob.arr[k]=A.arr[j];
             j++;  
         }
     }
     else
     {
        for(;k<x;k++)
         {
             ob.arr[k]=arr[i];
             i++;
         }
     }
     return ob;
     }
    void display()
    {
        for(int i=0;i<n;i++)
        System.out.print(arr[i]+" ");
    }
public static void Mixer(String[] args) 
{
Mixer ob1,ob2,ob3;
ob1=new Mixer(5);
ob2=new Mixer(6);
System.out.print("\n1st Array Input\n");
ob1.accept();
System.out.print("\n2nd Array Input\n");
ob2.accept();
ob3=ob1.mix(ob2);
System.out.print("\n1st Array Values\n");
ob1.display();
System.out.print("\n2nd Array Values\n");
ob2.display();
System.out.print("\n3rd Array Values\n");
ob3.display();

}
}

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner