egonSchiele / grokking_algorithms

Code for the book Grokking Algorithms (https://amzn.to/29rVyHf)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

A problem in many binary search implementations

stackcats opened this issue · comments

The problem is in the assignment

mid = (low + high) / 2

It can lead to overflow in some language

Good to know, which language/languages can this be an issue?

C/C++, Java, etc

C/C++, Java, etc

Is there any example?

You have to round the mid number down manually

commented

Maybe it's better to use binary shift operator instead of dividing by two and type conversions? I guess most of all programmic languages have it.

I used it, during the grokking binary search algorythm:

$mid = ($low + $high) -shr 1
(0 + 5) -shr 1  # 2, ok
(0 + 7) -shr 1  # 3, ok

There is a problem with the conversion from float to integer, for example, PoSh round a float to nearest even, not to down:

[int]( (0 + 5) / 2 ) # 2, ok
[int]( (0 + 7) / 2 ) # 4, expect 3