Difference between basic binary search for upper bound and lower bound?

前端 未结 3 1500
情书的邮戳
情书的邮戳 2020-12-23 22:59

In the article http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=binarySearch, the author discusses binary search. He makes a distinction between findin

3条回答
  •  爱一瞬间的悲伤
    2020-12-23 23:24

    The two algorithms obviously differ in the condition of what should happen if there are is no true or no false value as is actually quite obvious from the code snippet: if you find the lowest value where the value is true and subtract 1 from this position to find the highest value yielding false an incorrect result is produced as there is no such object. Since the algorithms simply target different elements dealing with locating the appropriate element directly rather than having a special case also avoids having to deal with a special case, reducing the amount of code. Since special case code tends to be executed only once for each algorithm invocation it is likely to perform slightly worse than avoiding the special case. This is something which may be worth measuring.

    Note that the code example isn't C++ despite the question being tagged C++. As a result it isn't idiomatic C++. The typical approach in C++ to implement something like lower_bound() or upper_bound() is to use appropriate iterators. These algorithms wouldn't "complain" if there is no suitable element as they'd just produce an iterator the appropriate position, i.e., an iterator to the start for std::lower_bound() and a past-the-end iterator for std::upper_bound().

提交回复
热议问题