Saturday, October 3, 2015

[9.1] Merge tow sorted array

1. Example

a = {1,2,3,10}
b= {4,5,6,7}

c= merge a and b = {1,2,3,4,5,6,7,10}




2. Implementation


// Assume a has a large enough buffer 
// 
public void merge( int[] a , int[] b, int m , int n)
{
    


     //validate the input
     // if (  a!=null && b==null   )
     //     return;
     // if (  a ) 
     // a == null
     // b == null
     



     int k = m + n -1;
     int i = m - 1;
     int j = n - 1;



     
     while (  i >= 0 && j >= 0 )
     {
           if ( a[i] >  b[j]  )
           {
               a[k--] = a[i--];
           }
           else 
           {
               a[k--] = b[j--];
           }
     }





     while (  j >= 0 )
     {
           a[k--] = b[j--];
     }


     

}


3. Similar ones

No comments:

Post a Comment