0

As we know there are various ways to get the middle element/index for a given sub-array(during recursive calls). Also we have to take care of overflow, large value of low/high condition as well, so which one should we prefer?

Method 1

mid = (low + high) / 2

Method 2

mid = low + (high - low) / 2
Wasit Shafi
  • 854
  • 1
  • 9
  • 15
  • This depends on language. In Python and many other languages you don't need to worry about overflow so the CPython builtin [uses `mid = (low + high) // 2`](https://github.com/python/cpython/blob/master/Lib/bisect.py#L31). The third option you present is logically wrong. See [this](https://cs.stackexchange.com/questions/80415/why-is-binary-search-using-this-weird-thing-to-calculate-middle) on CS.SE. – ggorlen Sep 02 '20 at 05:15
  • @ggorlen yes, third is wrong, its a mistake, sorry for that...:) – Wasit Shafi Sep 02 '20 at 05:27

1 Answers1

0

The third option is logically wrong. Both the first option and second option are logically correct but the first method can lead you to integer overflow. So, your second method is more appropriate to use.

Shovo
  • 133
  • 2
  • 9