Merge Two Sorted Arrays Using Objects in Java and Python
Merge two sorted arrays using objects with algorithm, explanation, Java class solution and simple Python solution for ISC students.
Question:
A class Mixer has been defined to merge two sorted integer arrays in ascending order.
The class contains an integer array arr[] and integer n. It has a constructor, accept(), mix(Mixer A) and display().
Specify the class Mixer, giving details of the constructor, accepting elements, merging another object array and displaying the result.
Algorithm:
Step 1: Start.
Step 2: Create class Mixer with array arr and size n.
Step 3: In the constructor, store the size and create the array.
Step 4: In accept(), input n elements into the current object array.
Step 5: In mix(Mixer A), create a result object B with combined size of both arrays.
Step 6: Copy all elements of the parameter object A into B.
Step 7: Copy all elements of the current object into the remaining positions of B.
Step 8: Sort B.arr in ascending order using nested loops and swapping.
Step 9: Return object B from the mix() method.
Step 10: In main(), create two Mixer objects, merge them and display all three arrays.
Step 11: Stop.
Explanation:
This question tests object handling. Each Mixer object owns its own array, so two arrays are stored in two different objects rather than as two simple local arrays.
The mix() method receives another Mixer object as a parameter. Inside the method, this refers to the object that called the method, while A refers to the object passed as argument.
A new object B is created to store the merged result. The program first copies both arrays into B.arr and then sorts the combined array.
Returning a Mixer object is important because the merged array should also behave like a normal Mixer object. This matches the ISC theory requirement for Mixer mix(Mixer A).
The array-copying loop and sorting loop are deliberately separate. First the result object receives all values from both source objects; only after the merged storage is complete does the nested loop compare indexes and swap values into ascending order.
The program merges two sorted arrays by comparing their current elements. Since both arrays are already sorted, the smallest available value must be at the current position of one of the arrays. Separate indexes are maintained for the first array, second array and merged array. The smaller current value is copied into the merged array and that array index is advanced. When one array finishes, the remaining values of the other array are copied directly. This preserves sorted order without sorting again from scratch.
Java Program:
/**
* The class Mixer merges two sorted arrays stored in separate objects.
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
* @Question Year : ISC 2014 Question 8 (Theory)
*/
import java.util.Scanner;
class Mixer
{
int arr[];
int n;
static Scanner sc = new Scanner(System.in);
Mixer(int nn)
{
n = nn;
arr = new int[n];
}
void accept()
{
System.out.println("* Input the Array *");
for(int i = 0; i < n; i++)
{
System.out.print("Enter Element [" + (i + 1) + "] : ");
arr[i] = sc.nextInt();
}
}
Mixer mix(Mixer A)
{
int size = this.arr.length + A.arr.length;
Mixer B = new Mixer(size);
int x = 0;
// First copy the parameter object's array into the result object.
for(int i = 0; i < size; i++)
{
if(i < A.arr.length)
B.arr[i] = A.arr[i];
else
{
B.arr[i] = this.arr[x];
x++;
}
}
// Sort the merged array in ascending order.
for(int i = 0; i < size - 1; i++)
{
for(int j = i + 1; j < size; j++)
{
if(B.arr[i] > B.arr[j])
{
int temp = B.arr[i];
B.arr[i] = B.arr[j];
B.arr[j] = temp;
}
}
}
return B;
}
void display()
{
for(int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[])
{
System.out.print("Enter size of the 1st array : ");
int p = sc.nextInt();
Mixer obj1 = new Mixer(p);
obj1.accept();
System.out.print("Enter size of the 2nd array : ");
int q = sc.nextInt();
Mixer obj2 = new Mixer(q);
obj2.accept();
Mixer obj3 = obj2.mix(obj1);
System.out.print("The 1st Array is : ");
obj1.display();
System.out.print("The 2nd Array is : ");
obj2.display();
System.out.print("The Merged Array is : ");
obj3.display();
}
}Equivalent Python Program:
# Read the matrix or array size and store the values for indexed processing.
# Helper functions keep repeated calculations separate from the main logic.
# Nested loops are used because each row/column or array position must be checked.
# Print the processed array or matrix in the required output format.
class Mixer:
def __init__(self, nn):
self.n = nn
self.arr = []
def accept(self):
print("* Input the Array *")
for i in range(self.n):
value = int(input("Enter Element [" + str(i + 1) + "] : "))
self.arr.append(value)
def mix(self, A):
B = Mixer(self.n + A.n)
for i in range(A.n):
B.arr.append(A.arr[i])
for i in range(self.n):
B.arr.append(self.arr[i])
for i in range(len(B.arr) - 1):
for j in range(i + 1, len(B.arr)):
if B.arr[i] > B.arr[j]:
temp = B.arr[i]
B.arr[i] = B.arr[j]
B.arr[j] = temp
return B
def display(self):
for i in range(len(self.arr)):
print(self.arr[i], end=" ")
print()
p = int(input("Enter size of the 1st array : "))
obj1 = Mixer(p)
obj1.accept()
q = int(input("Enter size of the 2nd array : "))
obj2 = Mixer(q)
obj2.accept()
obj3 = obj2.mix(obj1)
print("The 1st Array is : ", end="")
obj1.display()
print("The 2nd Array is : ", end="")
obj2.display()
print("The Merged Array is : ", end="")
obj3.display()Output:
Leave a Reply
Your email address will not be published. Comments are reviewed before appearing publicly.