Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between mid=(beg+end)/2 and mid=beg+(end-beg)/2 in binary search?

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.

like image 554
Pegasus Avatar asked Jan 08 '14 14:01

Pegasus


People also ask

How does binary search work?

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.

What happens if the match is found in binary search algorithm?

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.

What is the time complexity of binary search algorithm?

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

How many guesses does it take to get a binary search?

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.


1 Answers

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.

like image 157
Mike Seymour Avatar answered Nov 15 '22 17:11

Mike Seymour