C45 Answer


#include <stdio.h>
#include <stdlib.h>

/* Puzzle C45 -- fill a third array with the elements
|                two sorted arrays have in common
|
|  Write function that looks at two arrays and fills a
|  third array with the elements that are common to the
|  first two arrays. The first two array are sorted
|  into ascending order.
|
|  The third array has only one copy
|  of each element in common with the other two arrays.
|  The first two arrays may be of unequal sizes.
|  Return the number of elements in the third array.
|
*/
int commonElementsSorted( int arrA[], int sizeA,
                    int arrB[], int sizeB,
                    int out[],  int sizeOut )
{
  int eleA ;
  int ixa,  ixb ;
  int countOut = 0;
  
  /* Only one pass is needed over the second array */
  ixb = 0;
  
  /* look sequentially at elements in arrA */
  for ( ixa=0; ixa<sizeA; ixa++ )
  {
    eleA = arrA[ixa];
    
    /* check if eleA is also in arrB */
    /* since arrB is sorted, look only until an element */
    /* larger than eleA is found */
    for ( ; ixb<sizeB && arrB[ixb]<eleA; ixb++ ) ;
   
    /* add it to out if it is not already there */
    if ( eleA==arrB[ixb] )
    {
      /* if an element is already there it will be at the end */
      if ( countOut>0 && out[countOut-1] != eleA )
      {
        out[countOut] = eleA ;
        countOut++ ;
      }
      
      /* if nothing in the array yet, add this element */
      if ( countOut==0 )
      {
        out[0] = eleA ;
        countOut = 1 ;
      }
    }
  }
  return countOut ;
}