传统的二分查找是为了寻找目标数在一个有序数组中是否存在的问题。返回值为布尔型变量(true or false)。但是有时候需要知道更多信息,比如如果存在,那么在数组中该数出现的第一个位置(left most)和最后一个位置的索引是多少?如果不存在,那么如果把该数插入到数组中去,应该插入到哪个位置?
所以需要深入一步探索二分查找算法。C++中给出了几个库函数binary_search(),lower_bound() 和 upper_bound()。
binary_search()
Test if value exists in sorted sequence
Returns true if any element in the range [first,last) is equivalent to val, and false otherwise.
The elements are compared using operator < <script type="math/tex" id="MathJax-Element-1"><</script> for the first version, and comp for the second. Two elements, a and b are considered equivalent if (!(a < <script type="math/tex" id="MathJax-Element-2"><</script>b) && !(b < <script type="math/tex" id="MathJax-Element-3"><</script>a)) or if (!comp(a,b) && !comp(b,a)).
The elements in the range shall already be sorted according to this same criterion (operator< or comp), or at least partitioned with respect to val.
The function optimizes the number of comparison