In this tutorial you will learn about the Java Program to Merge Two Sorted Arrays and its application with practical example.
Java Program to Merge Two Sorted Arrays
In this tutorial, we will learn to create a Java program that will Merge Two sorted Arrays using Java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- For loop in Java programming.
- Arithmetic operations in Java Programming.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 |
Step 1 :- Initialize the program. Step 2 :- Declaring the variables for the program. Step 3 :- Taking the array one and two from the user. Step 4 :- Merging the two arrays. Step 5 :- Printing the merged array to the user. Step 6 :- End the program. |
Merging Two Arrays.
In this program, First, we will declare arrays one and two for the program. Then we will find the combined length for the merged array. After that, we will merge both the array. Then we will print the elements of the merged two sorted arrays to the user with the help of the print function.
With the help of this program, we can merge Two Sorted Arrays in an Array.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
//Java Program to Merge Two Sorted Arrays import java.util.Arrays; public class MergeSortedArray{ //Body of the main function. public static void main(String[] args) { // Declaring the variables for the program. // first array. int[] x = { 12, 21, 32, 45, 56 }; // second array. int[] y = { 55, 66, 98, 78, 85 }; // determines length of firstArray. int arry1 = x.length; // determines length of secondArray int arry2 = y.length; // resultant array size int arrymerged = arry1 + arry2; // create the resultant array int[] z = new int[arrymerged]; // using the pre-defined function arraycopy System.arraycopy(x, 0, z, 0, arry1); System.arraycopy(y, 0, z, arry1, arry2); // prints the resultant array //Printing the array 1 System.out.println("Array 1 = "); System.out.println(Arrays.toString(x)); //Printing the array 2 System.out.println("Array 2 = "); System.out.println(Arrays.toString(y)); //Printing the merged array System.out.println("merged array = "); System.out.println(Arrays.toString(z)); } } |
Output:-
In the above program, we have first initialized the required variable.
- x = it will hold the integer value.
- y = it will hold the integer value.
- z = it will hold the integer value.
Finding the size of the arrays.
Program Code to Merge Two Arrays.
Printing output of the program.