您的位置:首页 > 其它

STL: lower_bound(·) and upper_bound(·)

2016-12-11 02:59 288 查看

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: