954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

help with recursion

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

skeet123
Newbie Poster
20 posts since Nov 2004
Reputation Points: 10
Solved Threads: 0
 

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))
chrisbliss18
Posting Shark
917 posts since Aug 2005
Reputation Points: 38
Solved Threads: 25
 

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 >>

aj.wh.ca
Junior Poster in Training
53 posts since Mar 2005
Reputation Points: 12
Solved Threads: 1
 

Thanks both of you for your reply.

skeet123
Newbie Poster
20 posts since Nov 2004
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You