Hi folks,
I did a program to find a number at a lower bound position and upper bound position. For example,
this is my array values
1 1 2 3 5 5 5 5 7 8 9 10
if i search lower position for 5 , it will return 4 . and for upper bound it will return 7.
Actually i did a two function to find the numbers where it is locating for lower and upper bound.
int binarylower(int a[],int m,int l,int u)
{
int mid,c=0;
if(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
{
c=m;
return binarylower(a,m,l,mid-1);
}
else if(m<a[mid])
{
return binarylower(a,m,l,mid-1);
}
else
{
return binarylower(a,m,mid+1,u);
}
}
else
return l;
}
int binaryupper(int a[],int m,int l,int u)
{
int mid,c=0;
if(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
{
c=m;
return binaryupper(a,m,mid+1,u);
}
else if(m<a[mid])
{
return binaryupper(a,m,l,mid-1);
}
else
{
return binaryupper(a,m,mid+1,u);
}
}
else
return u;
}
Now i need only one function to find the lower and upper position. so i added extra parameter called 'mode' in that function. if mode value is 0, it will return lower position otherwise it will return upper position. This is my program
int binary(int a[],int m,int l,int u,int uorl)
{
int mid,c=0;
if(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
{
c=m;
if (uorl==0)
return binary(a,m,l,mid-1,0);
else
return binary(a,m,mid+1,u,1);
}
else if(m<a[mid])
{
return binary(a,m,l,mid-1,0);
}
else
{
return binary(a,m,mid+1,u,0);
}
}
else
{
if (uorl==0)
return l;
else
return u;
}
}
But i couldn't get the correct answer from the above function. If any one knows the solution please help me