Skip to content

Unexpected/undocumented binary_search behavior with duplicates #51817

Closed
@scottjmaddox

Description

@scottjmaddox

slice::binary_search (and perhaps its cousins?) behave in a fairly unexpected (and undocumented) way in the presence of duplicates:

let s = &[0, 1, 1, 1, 1, 2];
// What I would expect:
assert_eq!(s.binary_search(&1), Ok(1));
// Actual result:
assert_eq!(s.binary_search(&1), Ok(4));

While not strictly a bug (since the documentation does not state a particular behavior in this case) it would be fairly simple to tweak the implementation to provide the more expected behavior of returning the first match. Either way, it would be preferable if the behavior were documented.

Making the change at this point might result in some unexpected code breakage, even though the behavior is not documented. In order to ease the transition, it may be best to rename the current implementation to reverse_binary_search or similar, and provide the expected implementation for binary_search.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions