I was wondering if it is possible to find the closest element in a List
for a element that is not there.
For example if we had the valu
There are two methods to achieve the result-
I prefer to use the lower_bound method, it's short :)
int pos=lower_bound(v.begin(),v.end(),value);
if(pos!=0&&target!=v[pos])
if(abs(v[pos]-value)>abs(value-v[pos-1]))
pos=pos-1;
For binary search, you can refer to the above answers, as my code will seem like a copy paste of their code. Note that I have declared the array globally here.
binarysearch(int low,int high,int val)
{
if(val<=arr[0])
return 0;
if(val>=arr[n-1])
return arr[n-1];
while(low<=high)
{
int mid=(low+high)/2;
if(v[mid]>val)
return binarysearch(low,mid-1,val);
else if(v[mid]=abs(val-v[high]))
return high;
else
return low;
}