It is a problem from C++ primer fifth edition problem 3.26, I don't know the difference between them ? May be the second one can avoid overflow.
The working of binary search can be clearly understood by an analogy of alphabets in English. step 1: Choose which letter in alphabets is to find using binary search say "L". step 2: In binary search, the searching point moves to the middle element in of the alphabets say "M" and then decide which direction the searching point is to move.
If the match is found then, the location of middle element is returned otherwise, we search into either of the halves depending upon the result produced through the match. Binary search algorithm is given below.
Binary search is a mechanism used to find the given elements from the sorted array by continuously halving the array and then searching specified elements from a half array. And the process goes on till the match is found. It works only the sorted data structures. The time complexity of the binary search algorithm is O (log n).
Similarly for 32 elements, binary search will require at most 6 guesses to get the answer. We can see a pattern being formed here i.e., we require one more guess to get the result if the number of elements is doubled.
May be the second one can avoid overflow.
Exactly. There's no guarantee that beg+end
is representable; but in the second case the intermediate values, as well as the expected result, are no larger than end
, so there is no danger of overflow.
The second form can also be used for affine types like pointers and other random-access iterators, which can be subtracted to give a distance, but not added together.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With