当前位置:网站首页>[daily question on niuke.com] two point search

[daily question on niuke.com] two point search

2022-06-12 05:29:00 cbdgz

Title Description :
Given an ordered array of known length , Use binary search to find the first subscript greater than or equal to its value ( Subscript position from 1 Start )

Core code

int Bsearch(int v,vector<int>a,int n)
{
       if(v>a[n-1])return n+1;
    if(v<a[0])return 1;
    int i=0,j=n-1,ans=n+1;
    while(i<=j)
    {
    int mid=(j+i)/2;
    if(v==a[mid])
    {
    
    ans=mid;
    break;
    }
    if(v>a[mid])i=mid+1;
    if(v<a[mid])j=mid-1;
    }
    if(ans==n+1)return i;
    else{
    
    int k=ans;
    while(k>0&&a[k]==v)--k;
    return k+2;
    }
    
}
原网站

版权声明
本文为[cbdgz]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010616200663.html