In: Computer Science
Write a program in java which has two arrays of size 4 and 5; merge them and sort.
I have implemented the required code in Java.
And also provided the output of the respective code.I hope this will help.
Source code:
Main.java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
//array of length 4
int[] array1 = {33,88,11,55};
//array of length 5
int[] array2 = {22,44,66,99,77};
//Calculating sum of length of two arrays
int length = array1.length + array2.length;
System.out.println("First Array is: ");
for (int i = 0; i < array1.length; i++) {
System.out.print(" " + array1[i]);
}
System.out.println(" ");
System.out.println("Second Array is: ");
for (int i = 0; i < array2.length; i++) {
System.out.print(" " + array2[i]);
}
//Creating a resulting array of the calculated length
int[] result = new int[length];
int position = 0;
//for each loop to add array1 elements to the resulting array
for (int element: array1) {
result[position] = element;
position++;
}
//for each loop to add array2 elements to the resulting array
for (int element: array2) {
result[position] = element;
position++;
}
Arrays.sort(result);
System.out.println("\nThe resulting array after merging and sorting
two arrays is: ");
for (int i = 0; i < length; i++) {
System.out.print(" " + result[i]);
}
}
}
Output: