Java Program to Merge Two Arrays

This is the Java Program to Merge Two Arrays in Order.

Problem Description

Given two arrays of integers, merge them into a single sorted array in order.

Example:
Array1: [1,2,3,4,5]
Array2: [2,3,6,7,8]

Output:

Array = [1,2,2,3,3,4,5,6,7,8]

Problem Solution
advertisement
advertisement

Create a new array of size equal to the sum of the sizes of the two arrays. Now, compare the first elements of the first two arrays and put the smaller element in the new array. Increment the index counter of the array which contains the small element and continues the process. If the elements of any of the arrays are completely copied, then copy the remaining elements of the other array, into the new array.

Program/Source Code

Here is the source code of the Java Program to Merge Two Arrays in Order. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.

  1.  
  2. // Java Program to Merge Two Arrays in Order.
  3.  
  4. import java.io.BufferedReader;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7. import java.util.Arrays;
  8.  
  9. public class InOrderMerge {
  10.     // Function to merge the arrays
  11.     static int[] mergeArrays(int[] arrayOne,int[] arrayTwo)
  12.     {
  13.         int totalLength=arrayOne.length +arrayTwo.length;
  14.         int[] c=new int[totalLength];
  15.         int j,k,index=0;
  16.         j=0;
  17.         k=0;
  18.         while((j!=arrayOne.length) && (k!=arrayTwo.length)){
  19.             if(arrayOne[j]<=arrayTwo[k])
  20.             {
  21.                 c[index++]=arrayOne[j++];
  22.             }
  23.             else
  24.             {
  25.                 c[index++]=arrayTwo[k++];
  26.             }
  27.         }
  28.         while(k!=arrayTwo.length)
  29.         {
  30.             c[index++]=arrayTwo[k++];
  31.         }
  32.         while(j!=arrayOne.length)
  33.         {
  34.             c[index++]=arrayOne[j++];
  35.         }
  36.         return c;
  37.     }
  38.     // Function to read input and display the output
  39.     public static void main(String[] args){
  40.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  41.         int m, n;
  42.         System.out.println("Enter the size of the two arrays");
  43.         try {
  44.             n = Integer.parseInt(br.readLine());
  45.             m = Integer.parseInt(br.readLine());
  46.         }
  47.         catch (IOException e)
  48.         {
  49.             System.out.println("Invalid input");
  50.             return;
  51.         }
  52.         int[] arrayOne = new int[n];
  53.         int[] arrayTwo = new int[m];
  54.         System.out.println("Enter the first array elements");
  55.         int i,j;
  56.         for(i=0; i<arrayOne.length; i++){
  57.             try {
  58.                 arrayOne[i] = Integer.parseInt(br.readLine());
  59.             }
  60.             catch (IOException e)
  61.             {
  62.                 System.out.println("Invalid array element. Enter it again");
  63.                 i--;
  64.             }
  65.         }
  66.         System.out.println("Enter the second array elements");
  67.         for(i=0; i<arrayTwo.length; i++){
  68.             try {
  69.                 arrayTwo[i] = Integer.parseInt(br.readLine());
  70.             }
  71.             catch (IOException e)
  72.             {
  73.                 System.out.println("Invalid array element. Enter it again");
  74.                 i--;
  75.             }
  76.         }
  77.         Arrays.sort(arrayOne);
  78.         Arrays.sort(arrayTwo);
  79.         int[] mergedArray=mergeArrays(arrayOne,arrayTwo);
  80.         System.out.println("The merged array is");
  81.         for(i=0;i<mergedArray.length;i++)
  82.         {
  83.             System.out.print(mergedArray[i]+" ");
  84.         }
  85.     }
  86. }
Program Explanation

1. In function mergeArrays(), a new array c is created whose size is equal to the total size of the two arrays.
2. The loop while((j!=arrayOne.length) && (k!=arrayTwo.length)) merges the two array in ascending order, until one of the arrays is completely merged.
3. The loops while(k!=arrayTwo.length) and while(j!=arrayOne.length) merges the remaining components of any array into the final array c.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

Time Complexity: O(n*log(n) + m*log(m)) where n is the number of elements in the first array and m is the number of elements in the second array.

Runtime Test Cases
 
 
Case 1 (Simple Test Case):
 
Enter the size of the two arrays
5
5
Enter the first array elements
1
2
3
4
5
Enter the second array elements
2
3
6
7
8
The merged array is
1 2 2 3 3 4 5 6 7 8
 
Case 2 (Simple Test Case - another example):
 
Enter the size of the two arrays
4
5
Enter the first array elements
89
45
32
6
Enter the second array elements
24
456
23
567
34
The merged array is
6 23 24 32 34 45 89 456 567

Sanfoundry Global Education & Learning Series – Java Programs.

advertisement

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.