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