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

let mid = (lo + hi) / 2; Overflows #2

Open
kaltu opened this issue Dec 22, 2023 · 2 comments · May be fixed by #5
Open

let mid = (lo + hi) / 2; Overflows #2

kaltu opened this issue Dec 22, 2023 · 2 comments · May be fixed by #5

Comments

@kaltu
Copy link

kaltu commented Dec 22, 2023

let mid = (lo + hi) / 2;

Overflow may happen in (lo + hi) where (lo, hi): (usize, usize)

consider changing it to lo + (hi - lo) / 2

This is not an issue in the original Python implementation because Python handles overflow to large numbers automatically
But that is not the case for Rust

@kaltu
Copy link
Author

kaltu commented May 7, 2024

https://research.google/blog/extra-extra-read-all-about-it-nearly-all-binary-searches-and-mergesorts-are-broken/

Thanks for the added context.
But please be aware that the bit shift trick demonstrated without detailed elaboration in the post is taking advantage of signed int. In Rust where unsigned integer type usize is used, the trick won't work.

As for why bit shift works for singed integers, when signed integers overflow in addition, the sign bit is incorrectly flipped, but this error can be salvaged by blindly shifting every bit to the right, including the flipped sign bit. I.e. the unsigned bit shift right >>> in Java, or temporarily cast to unsigned integer before bit shift right >> in C/C++. But when unsigned integers overflow, the carry is lost, using a shift right will fill the most significant bit with 0 instead of the correct 1.

@kaltu kaltu closed this as completed May 7, 2024
@kaltu kaltu reopened this May 7, 2024
@musicinmybrain musicinmybrain linked a pull request May 8, 2024 that will close this issue
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

Successfully merging a pull request may close this issue.

2 participants