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;
}