Binary Search approach

void place(vector &v,ll value)
{
int m=v.size();
for(int i=0;i<m;i++)
{
if(value<v[i])
{
v[i]=value;
break;
}
}
}
The above piece of code uses linear search to find an element larger than the given value and replace it with the given value.Below is the implementation of binary search with same logic.Can anyone tell me that where the binary search algorithm fails.Also It is assured that the given value will always be smaller than the largest element of the array.
int n=a.size(),f=0,l=n-1,mid;
while(true)
{
mid=(f+l)/2;
if((l==0 || mid==0) && a[mid]>value)
{
a[mid]=value;
break;
}
if((f==(n-1) || mid==(n-1)) && a[mid]>value)
{
a[mid]=value;
break;
}
if(value<a[mid])
{
if(a[mid-1]<=value)
{
a[mid]=value;
break;
}
else
l=mid-1;
}
else if(value>a[mid])
{
if(a[mid+1]>=value)
{
a[mid+1]=value;
break;
}
else
f=mid+1;
}
else
{
int j=mid;
while(a[j]==a[mid])
{
if(a[j+1]>a[mid])
{
a[j+1]=value;
break;
}
else
j++;

           }
           break;
       }
    }
1 Like

I wanna ask you that are you trying to write binary search algo?

Yes but not the usual binary search. I wish to find the element which is just larger than the given value.

I guess you are talking about upper bound in binary search right?

Yes

Hello this is Gulshan Negi
Well, I had checked it on Google and found that the error in the given code is that it does not handle the case where the binary search reaches the boundary of the array (i.e., f or l becomes 0 or n-1, respectively) and the value being searched for is smaller than the value at that boundary. In such cases, the code tries to access a[mid], which may result in an index out of bounds error or unexpected behavior. To fix this error, you can add an additional check at the beginning of the while loop to ensure that f and l are not at the boundaries before accessing a[mid].
I hope it will give you any idea.
Thanks

Please write code in code block. This is unreadable.