user466534
user466534

Reputation:

use link to find maximum in array

Guys, following code stops working because of runtime error

#include<iostream>
using namespace std;
struct node
{
  int item;
  node *l;
  node *r;
  node(int x)
  {
    item=x; l=0;r=0;  
  }
};

typedef node *link;

link Max(int a[],int l,int n)
{
   int m=l+(l+n)/2;
   link x=new node(a[m]);

   if(l==n)  return x;

   x->l=Max(a,l,m);
   x->r=Max(a,m+1,n);
   int u=x->l->item;
   int v=x->r->item;
   if(u>v)  x->item=u;
   else x->item=v;

   return x;         
}

int main(){
link y;

int a[]={12,3,5,4,7,6,20,11,10,9};

int n=sizeof(a)/sizeof(a[0]);
y=Max(a,0,n-1);

cout<<y->item<<endl;

return 0;
}

i dont understand what is reason,i have declared struct node as necessary,use recursive function correctly i think and what is another reason why it does not work?please give me some advices,

Upvotes: 0

Views: 97

Answers (1)

flipchart
flipchart

Reputation: 6578

The code is giving me a stack overflow exception. Your calculation of the variable m is off: it should probably be something like int m = l + (n-l)/2; which will give you the offset from l for half of the remaining elements. Your current implementation gives "midpoint" values outside of the range [l,n] hence the function recurses indefinitely

Upvotes: 2

Related Questions