Saturday, March 29, 2014

Java Program to merge two sorted Arrays

To merge two sorted array is one of the very commonly asked Interview question.

below is my code of merging two sorted arrays with explanation




import java.util.Arrays;
public class MergeSortedArray {  

  int [] a = {1,3,5,7,9,10};// -----> first sorted array
  int [] b = {2,4,6,8,8};   // -----> Second sorted array 

  public static void main(String[] args) {
    MergeSortedArray msa = new MergeSortedArray();
    /*

     * printing all three arrays 

     */  

  System.out.println("First Sorted Array is:");
  System.out.println(Arrays.toString(msa.a));
  System.out.println();
  System.out.println("Second Sorted Array is:");
  System.out.println(Arrays.toString(msa.b));
  System.out.println();
  System.out.println("Merged Sorted Array is:");
  System.out.println(Arrays.toString(

                            msa.getSortedMergedArray(msa.a, msa.b)));
  } 

   /*

    *Method to merged array which will be to get combined sorted array

    */

  public  int[] getSortedMergedArray(int[] a, int[] b) {  

   // defining new array of size first+second array 

    int[] mergedArray = new int[a.length + b.length];
    int i = 0, j = 0, k = 0;  

    /*

    *iterating till last element of any of the array

    * We only loop till we reach at the end of any of the two arrays

    */ 


    while (i < a.length && j < b.length) {
         if (a[i] < b[j]) {
             mergedArray[k++] = a[i++];
         }

         else {       
             mergedArray[k++] = b[j++];  
         }
     }  

     /* 

      * loop to add reaming elements of either of the remaining array  
     */  

     while (i < a.length) { 
         mergedArray[k++] = a[i++];
     }

     while (j < b.length) {
         mergedArray[k++] = b[j++];
     }

     return mergedArray;
 }
}

OUTPUT:
===========================================================================

First Sorted Array is:
[1, 3, 5, 7, 9, 10]

Second Sorted Array is:
[2, 4, 6, 8, 8]

Merged Sorted Array is:
[1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10]

No comments :

Post a Comment