当前位置:网站首页>lower_bound,upper_bound,二分

lower_bound,upper_bound,二分

2022-06-11 04:32:00 superkcl2022

#include <iostream>
using namespace  std;


/** * lower_bound 若有多个等于target的数,返回最左边的那个数,否则返回 > target的那个数的下标 * 如果 tar最小返回0,如果tar最大返回数组最大值下标+1 * * * 1. target的值比cnt[0]小,while循环直到 l == r == 0, a[0] >= tar 返回0 * 2. target最大, 会一直执行这条语句 a[mid] < tar ,index的值不变 * */

/** * 二分,log级别,未查询到叶子节点,即可停止,而lower_bound停不下来,一直到叶子节点 * */

int lower_bound(int a[],int l,int r,int tar){
    
    int index = r+1;
    while(l <= r){
    
        int mid = l + (r-l)/2;
        if(tar > a[mid]) l = mid + 1;  //中间值小了
        else {
     // a[mid] == tar时,r = mid - 1
            index = mid;
            r = mid - 1;
        }
    }
    return index;
}

int upper_bound(int a[],int l,int r,int tar){
    
    int index = r+1;
    while(l <= r){
    
        int mid = l + (r-l)/2;
        if(tar >= a[mid]) l = mid + 1;
        else{
    
            index = mid;
            r = mid - 1;
        }
    }
    return index;
}

int main() {
    

    int cnt[] = {
    2,4,4,5,7,8,9};
    cout << lower_bound(cnt,0,sizeof(cnt)/sizeof(int)-1,14) << endl;
    cout << upper_bound(cnt,0,sizeof(cnt)/sizeof(int)-1,4) << endl;
    return 0;
}


原网站

版权声明
本文为[superkcl2022]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_37642480/article/details/125076072