Lower_bound functions and Upper_bound functions in C + +

Source: Internet
Author: User

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 + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.