STL: lower_bound(·) and upper_bound(·)

来源:互联网 发布:身份证 复制 知乎 编辑:程序博客网 时间:2024/05/18 20:50

Lower Bound

This is a problem I came across in Google interview, and I was caught off guard. The interviewer asked me to implement the lower_bound(·) function in STL. Here is the code:

int lower_bound(int *array, int size, int key){    int first = 0, middle;    int half, len;    len = size;    while(len > 0) {        half = len >> 1;        middle = first + half;        if(array[middle] < key) {                 first = middle + 1;                      len = len-half-1;               }        else            len = half;             }    return first;}

Upper Bound

Similarly we have:

int upper_bound(int *array, int size, int key){    int first = 0, len = size-1;    int half, middle;    while(len > 0){        half = len >> 1;        middle = first + half;        if(array[middle] > key)                 len = half;        else{            first = middle + 1;                len = len - half - 1;        }    }    return first;}
0 0