27

I was reading about binary search...I know that the traditional way of finding mid value is like

mid=(hi+lo)/2

But i also see that to avoid overflow mid value is calculated like that

mid=lo+(hi-lo)/2

But why?? I couldn't find the actual reason..Can anyone give me the reason with example?? It is different from other question because other questions didn't have the answer that i wanted with example...

  • 7
    The reason is in your question, to avoid overflow. – harold Aug 29 '14 at 15:24
  • 1
    This question is off-topic because it's an answer with a question mark. – Quentin Aug 29 '14 at 15:25
  • i didn't get any example..i wanted examples.. –  Aug 29 '14 at 15:30
  • Suppose hi and lo were pointers (or iterators in C++). The sum of two pointers have no meaning. The difference of two pointers does, it's an integer. Adding an integer to a pointer makes senses as well. – user515430 Aug 29 '14 at 20:18

2 Answers2

40

Suppose you are searching a 4000000000-element array using 32-bit unsigned int as indexes.

The first step made it appear as though the searched element, if present, would be in the top half. lo's value is 2000000000 and hi's is 4000000000.

hi + lo overflows and produces a value smaller than the intended 6000000000. It actually produces 6000000000-232. As a result, (hi + lo) / 2 is a small value. It is not even between lo and hi!

From then on the search will be wrong (it will probably conclude that the element is absent even if it was there).

By contrast, even with the extreme values in this example, lo + (hi - lo) / 2 always computes an index halfway between hi and lo, as intended by the algorithm.

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
8

Mathematically speaking, they are equivalent.

In computer terms, mid=(hi+lo)/2 has fewer operations, but mid=lo+(hi-lo)/2 is preferred to avoid overflow.

Say the item you are searching are near the end of the array, then hi+lo is nearly 2*size. Since size can be almost as large as your maximum index, 2*size and thus hi+lo can overflow.

ikegami
  • 367,544
  • 15
  • 269
  • 518