Merge Arrays ISC 2014 Theory

A class Mixer has been defined to merge two sorted integer arrays in ascending order. Some of the members of the class are given below:

Class name: Mixer
Data members/instance variables:
int arr[]: to store the elements of an array.
int n: to store the size of the array.
Member functions:
Mixer(int num): constructor to assign n = num.
void accept(): to accept the elements of the array in ascending order without any duplicates.
Mixer mix(Mixer A): to merge the current object array elements with the parameterized array elements and return the resultant object.
void display(): to display the elements of the array.

Specify the class Mixer, giving details of the constructor, void accept(), Mixer mix(Mixer) and void display(). Define the main() function to create an object and call the functions accordingly to enable the task.

import java.io.*;
class Mixer{
    private int arr[];
    private int n;
    public Mixer(int num){
        n = num;
        arr = new int[n];
    }
    public void accept()throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter " + n + " integers:");
        int count = 0;
        int pos = 0;
        while(count < n){
            boolean found = false;
            System.out.print("Enter element " + (count + 1) + ": ");
            int elem = Integer.parseInt(br.readLine());
            for(int i = 0; i < n; i++){
                if(elem == arr[i]){
                    found = true;
                    break;
                }
            }
            if(!found){
                arr[pos++] = elem;
                count++;
            }
        }
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n - 1 - i; j++){
                if(arr[j] > arr[j + 1]){
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
    public Mixer mix(Mixer A){
        Mixer temp = new Mixer(this.n + A.n);
        int i = 0;
        for(int j = 0; j < A.n; j++)
            temp.arr[i++] = A.arr[j];
        for(int j = 0; j < this.n; j++)
            temp.arr[i++] = this.arr[j];
        return temp;
    }
    public void display(){
        for(int i = 0; i < n; i++)
            System.out.print(arr[i] + "\t");
        System.out.println();
    }
    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Size of first array: ");
        int n1 = Integer.parseInt(br.readLine());
        Mixer obj1 = new Mixer(n1);
        System.out.print("Size of second array: ");
        int n2 = Integer.parseInt(br.readLine());
        Mixer obj2 = new Mixer(n2);
        obj1.accept();
        obj2.accept();
        Mixer obj3 = obj1.mix(obj2);
        obj3.display();
    }
}

Leave a Reply