A problem in many binary search implementations
stackcats opened this issue · 6 comments
stackcats commented
The problem is in the assignment
mid = (low + high) / 2
It can lead to overflow in some language
ajh1143 commented
Good to know, which language/languages can this be an issue?
stackcats commented
C/C++, Java, etc
tiendq commented
C/C++, Java, etc
Is there any example?
knenkne commented
You have to round the mid number down manually
mitmih 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, okThere 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