Saturday 2 March 2013

Given 2 sorted arrays of size m and n+m(with n elements) , merge them into the latter..


/*
 * Java Program
*/


public class Solution {

      private int[] arr1;
      private int[] arr2;
      private int elementsInarr1 = 0;   //variable stores no. of elements in arr1 (n)
     
      //Initialize arr1 with n elements and arr2 with n+m elements
      public void initialize()
      {
             arr1 = new int[13];
             arr2 = new int[6];
             arr1[0]=7;
             arr1[1]=12;
             arr1[2]=14;
             arr1[3]=20;
             arr1[4]=25;
             arr1[5]=35;
             arr1[6]=40;
             elementsInarr1 = 7;
             arr2[0]=2;
             arr2[1]=5;
             arr2[2]=16;
             arr2[3]=24;
             arr2[4]=32;
             arr2[5]=34;
      }
     
      //Diplay contents of array.
      public void displayArray()
      {
             for(int n:arr1)
             {
                   System.out.print(" "+ n);
             }
      }
     
      public void inPlaceMerge()
      {
             int i = elementsInarr1-1;
             int pos = arr1.length-1;
             int j = arr2.length-1;
             while(i>=0 && j>=0)
             {
                    if(arr1[i] > arr2[j])
                    {
                          arr1[pos--] = arr1[i--];
                    }
                    else
                    {
                          arr1[pos--] = arr2[j--];
                    }
             }
           
             while(j>=0)
             {
                   arr1[pos--] = arr2[j--];
             }
      }
     
      public static void main(String args[])
      {
             Solution s = new Solution();
             s.initialize();
             s.inPlaceMerge();
             s.displayArray();
      }
}

1 comment:

  1. This question is picked up from amazon interview questions.
    Though question seemed easy, I was proceeding in wrong direction, it took me good 5-10 mins to identify the trick (start from end and not from beginning of both the arrays).
    After this question was very easy.

    ReplyDelete