I am having a problem with a recursion problem. I have been reading alot of threads on this subject here and other places. I think I understand what recursion is. I am just having a problem trying to figure out this problem. I am suppose to write a helper function for maxarray.


Searching an array Find the maximum element in an unsorted array
if (anArray has only one item)
maxArray(anArray) is that item
else if (anArray has more than one item)
maxArray(anArray) is maximum of
maxArray(left half of anArray) and
maxArray(right half of anArray)


In the call tree it looks like this:
1st level:
maxArray(<1,6,8,3>)
return max(maxArray(<1,6>), maxArray(<8,3>))

2nd level
maxArray(<1,6>) maxArray(<8,3>)

return max(maxArray(<1), maxArray(<6>)) return max(maxArray(<8), maxArray(<3>))

3rd level
maxArray(<1>) maxArray(<6>) maxArray(<8>) maxArray(<3)

I am suppose to write the helper function max. I have no idea how to get started. Any help on this would be much appreciated. Thank you.

you can see more info an call tree at this link:http://www.cs.wm.edu/~debbie/cs241/recursion/recursion.html


#12 searching an array

You don't necessarily need to make a max function, you could actually use a define like the following:

#define MAX(a, b) ((a) > (b) ? (a) : (b))

Hi,
Following should work fine

int max(int *array, int len)
{
  int n1,n2;
  if(len == 1) return array[0] ;


  n1 = max(array , len/2);
  n2 = max(array + len/2 , len - len/2) ;
  return (n1 > n2 ? n1 : n2) ;
}


int main()
{
   int A[] = {2,7,91,8,9,11} ;
   int B[] = {2,7,91,8,9} ;

   printf("\n%d ",max(&A[0], 6));
   printf("\n%d\n ",max(&B[0], 5));
}

<< moderator edit: added [code][/code] tags >>

Thanks both of you for your reply.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.