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

bsearch return unexpected value when using less or equal test #14994

Open
SlimBenAmor opened this issue Sep 12, 2024 · 1 comment
Open

bsearch return unexpected value when using less or equal test #14994

SlimBenAmor opened this issue Sep 12, 2024 · 1 comment

Comments

@SlimBenAmor
Copy link

As described in the comment of [bsearch_index](https://github.com/crystal-lang/crystal,

[2, 5, 7, 10].bsearch_index { |x, i| x >= 4 } # => 1
[2, 5, 7, 10].bsearch_index { |x, i| x > 10 } # => nil

which is correct. However, if we test with the following, we get unexpected result.

[2, 5, 7, 10].bsearch_index { |x| x <= 5}} # => nil
[2, 5, 7, 10].bsearch_index { |x| x <= 7} # => 0

I think there is a bug. And the problem seems to appear if the searched value in in the first half of the array (we will always get nil) or in the second half (we will always get 0).

@spuun
Copy link
Contributor

spuun commented Sep 13, 2024

It works as intended. If you read the docs for the method it mentions that "binary search needs the collection to be sorted in regards to the search criterion". I.e if you have a list sorted ascending you must use a greater than comparison, while if the list is sorted descending you must use a less than comparison.

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

2 participants