The functions of binary lookup in STL are three Lower_bound, Upper_bound, Binary_search. These three functions are applied to the ordered interval (which is also the premise of using a binary search), and the two functions are recorded below.
Forwarditer Lower_bound (forwarditer First, Forwarditer last,const _tp& val) algorithm returns a non-descending sequence [first, last] The position of the first greater than or equal to Val in the value.
Forwarditer Upper_bound (forwarditer First, Forwarditer last, const _tp& val) The algorithm returns a non-descending sequence of the position in the "number" of the value Val.
Lower_bound and Upper_bound are as follows:
1.lower_bound function Source code:
View Sourceprint?
01.
//这个算法中,first是最终要返回的位置
02.
int
lower_bound(
int
*array,
int
size,
int
key)
03.
{
04.
int
first =
0
, middle;
05.
int
half, len;
06.
len = size;
07.
08.
while
(len >
0
) {
09.
half = len >>
1
;
10.
middle = first + half;
11.
if
(array[middle] < key) {
12.
first = middle +
1
;
13.
len = len-half-
1
;
//在右边子序列中查找
14.
}
15.
else
16.
len = half;
//在左边子序列(包含middle)中查找
17.
}
18.
return
first;
19.
}
2.upper_bound function Source code:
View Sourceprint?
01.
int
upper_bound(
int
*array,
int
size,
int
key)
02.
{
03.
int
len = size-
1
;
04.
int
half, middle;
05.
06.
while
(len >
0
){
07.
half = len >>
1
;
08.
middle = first + half;
09.
if
(array[middle] > key)
//中位数大于key,在包含last的左半边序列中查找。
10.
len = half;
11.
else
{
12.
first = middle +
1
;
//中位数小于等于key,在右半边序列中查找。
13.
len = len - half -
1
;
14.
}
15.
}
16.
return
first;
17.
}
Lower_bound functions and Upper_bound functions in C + +