Merge two sorted arrays in Java

Java 8Object Oriented ProgrammingProgramming

Two sorted arrays can be merged so that a single resultant sorted array is obtained. An example of this is given as follows.

Array 1 = 1 3 7 9 10
Array 2 = 2 5 8
Merged array = 1 2 3 5 7 8 9 10

A program that demonstrates this is given as follows.

Example

 Live Demo

public class Example {
   public static void main (String[] args) {
      int[] arr1 = {11, 34, 66, 75};
      int n1 = arr1.length;
      int[] arr2 = {1, 5, 19, 50, 89, 100};
      int n2 = arr2.length;
      int[] merge = new int[n1 + n2];
      int i = 0, j = 0, k = 0, x;
      System.out.print("Array 1: ");
      for (x = 0; x < n1; x++)
      System.out.print(arr1[x] + " ");
      System.out.print("\nArray 2: ");
      for (x = 0; x < n2; x++)
      System.out.print(arr2[x] + " ");
      while (i < n1 && j < n2) {
         if (arr1[i] < arr2[j])
            merge[k++] = arr1[i++];
         else
            merge[k++] = arr2[j++];
      }
      while (i < n1)
      merge[k++] = arr1[i++];
      while (j < n2)
      merge[k++] = arr2[j++];
      System.out.print("\nArray after merging: ");
      for (x = 0; x < n1 + n2; x++)
      System.out.print(merge[x] + " ");
   }
}

Output

Array 1: 11 34 66 75
Array 2: 1 5 19 50 89 100
Array after merging: 1 5 11 19 34 50 66 75 89 100

Now let us understand the above program.

First the 2 sorted arrays arr1 and arr2 are displayed. The code snippet that demonstrates this is given as follows.

System.out.print("Array 1: ");
for (x = 0; x < n1; x++)
System.out.print(arr1[x] + " ");
System.out.print("\nArray 2: ");
for (x = 0; x < n2; x++)
System.out.print(arr2[x] + " ");

The sorted arrays are merged into a single array using a while loop. After the while loop, if any elements are left in arr1 or arr2, then they are added to the merged array. The code snippet that demonstrates this is given as follows.

while (i < n1 && j < n2) {
   if (arr1[i] < arr2[j])
      merge[k++] = arr1[i++];
   else
      merge[k++] = arr2[j++];
}
while (i < n1)
merge[k++] = arr1[i++];
while (j < n2)
merge[k++] = arr2[j++];

Finally the merged array is displayed. The code snippet that demonstrates this is given as follows.

System.out.print("\nArray after merging: ");
for (x = 0; x < n1 + n2; x++)
System.out.print(merge[x] + " ");
raja
Published on 07-Dec-2018 11:34:38
Advertisements