STL binary search function in

ForwardIter lower_bound (ForwardIter first, ForwardIter last, const _Tp & val) algorithm returns a non-decreasing sequence [first, last) is not less than a first value val position.

ForwardIter upper_bound (ForwardIter first, ForwardIter last, const _Tp & val) algorithm returns a non-decreasing sequence [first, last) in the first position is greater than the value val.

lower_bound and upper_bound shown below: If all the elements is less than val, returns the last position and the last position is out of range! ! ~

 

2. Insert: for example as follows:

An array num sequence: To insert a number 3,9,20,111 4,10,11,30,69,70,96,100 provided. pos position to be inserted under the standard, then

lower_bound = POS ( NUM , NUM + 8,3) - NUM , POS = 0. I.e. num array subscript 0 position.

pos = lower_bound (num, num + 8,9) -num, pos = 1. I.e. num array index position 1 (i.e. located at position 10).

pos = lower_bound (num, num + 8,111) -num, pos = 8. I.e. num index array is at position 8 (subscript but the upper limit is 7, so the next element returns the last element).

pos = upper_bound (num, num + 8,20) -num, pos = 3. I.e. num array subscript 3 position.

1.lower_bound function source code:

 

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:

 

 

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

Guess you like

Origin www.cnblogs.com/flyljz/p/10991942.html