Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A problem in many binary search implementations #92

Open
stackcats opened this issue Oct 9, 2018 · 5 comments
Open

A problem in many binary search implementations #92

stackcats opened this issue Oct 9, 2018 · 5 comments

Comments

@stackcats
Copy link

The problem is in the assignment

mid = (low + high) / 2

It can lead to overflow in some language

@ajh1143
Copy link

ajh1143 commented Dec 15, 2018

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

@stackcats
Copy link
Author

C/C++, Java, etc

@tiendq
Copy link

tiendq commented Apr 4, 2019

C/C++, Java, etc

Is there any example?

@knenkne
Copy link

knenkne commented Jun 26, 2019

You have to round the mid number down manually

@mitmih
Copy link

mitmih commented Jun 21, 2020

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants