C++ binary search

复制代码
void Util::bs30()
{
    int arr[]={10,20,30,40,50,60,70,80,90,100};
    int key=90;
    int idx=binarySearch29(arr,0,9,key);
    if(idx>-1)
    {
        cout<<"The key "<<key<<" found at "<<idx<<endl;
    }
    else
    {
        cout<<"The key "<<key<<" not found in array!"<<endl;
    }
    cout<<getTime()<<",finished in void Util::bs30()"<<endl;
}

int Util::binarySearch29(int arr[], int low, int high, int key)
{
    if(low<=high)
    {
        int mid=low+(high-low)/2;
        if(arr[mid]==key)
        {
            return mid;
        }
        else if(arr[mid]<key)
        { 
            return binarySearch29(arr,mid+1,high,key);
        }
        else
        {
            return binarySearch29(arr,low,mid-1,key);
        }
    }
    return -1;
}

void binarySearch14();

int main(int args, char **argv)
{
    try
    {
        binarySearch14();
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << '\n';
    }
}

void binarySearch14()
{
    Util ul;
    ul.bs30();
}
复制代码
./h1 0

 

posted @   FredGrit  阅读(45)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2020-06-09 HttpClient SendAsync
2020-06-09 WebRequest, WebRequest.Create GetResponse() GetResponseStream()
点击右上角即可分享
微信分享提示