A code in C to find maximum of an array using divide and conquer but it keeps throwing "stack overflow exception" . Help would be appreciated!
int a[10];
int find(int l,int h)
{
int x;
if(h==0)
{
x=0;
return x;
}
else
{
if(h==1)
{
if(a[0]>a[1])
{
x=0;
return x;
}
else
{
x=1;
return x;
}
}
else
{
int mid,z,y;
mid=(l+h)/2;
y=find(0,mid);
z=find(mid+1,h);
if(a[y]<a[z])
{
x=z;
}
else
{
x=y;
}
return x;
}
}
}
There are only limited variables and I don't see where the function can go into an infinite recursion.
int main()
{
int i,n,max,min,ans;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
ans=find(0,n-1);
printf("the maximum element is- %d\n",ans);
getch();
return 0;
}
his0or1catch all the cases, if not then it will keep re-cursing infinitely.l = 0andh = 2:mid = (0+2)/2 = 1; y=find(0,1); z=find(2,2);- Which looks correct but then look what thefind(2,2)will do:mid = (2+2)/2 = 2; y=find(0,2);<= We're back at our first test values.z=find(3,2);<= This just looks odd.