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
Make clarifications for binary_search
API
#124882
Comments
You can use let seek = 5;
let x = [5, 4, 3, 2, 1].binary_search_by(|probe| seek.cmp(probe));
assert_eq!(x, Ok(0)); It seems worth mentioning There are examples of reversing the comparator order for sorting a slice in reverse order. |
In the end I used search_by version, yes, but doc for regular version was confusing by not mentioning this slight requirement. |
If I specify a newtype that is "sorted" in "descending order" because I took an existing type which usually sorts in the usual order (say, u32) and inverted its comparator (possibly a The only sort order that matters for this is the comparator in Ord: the first index shall be the least element of the set according to the comparator, and the last index shall be the greatest element of the set according to the comparator. That is what is meant by "sorted", here. |
Not sure about that part use std::cmp::Ordering;
#[derive(Debug, PartialOrd, Eq, PartialEq)]
struct N(u32);
impl Ord for N {
fn cmp(&self, other: &N) -> Ordering {
self.0.cmp(&other.0).reverse() // is that inverted comparator
}
}
fn main() {
let mut vec = vec!(N(2), N(1), N(3), N(5), N(4)); // randomized order
vec.sort();
let result = vec.binary_search(&N(5));
println!("{vec:?} {result:?}"); // output [N(1), N(2), N(3), N(4), N(5)] Err(0)
} Is that what you meant? Sorted in ascending order for a human, but binary search yields error, because of |
Oh, I meant use std::cmp::Ordering;
#[derive(Debug, Eq, PartialEq)]
struct N(u32);
impl PartialOrd for N {
fn partial_cmp(&self, other: &N) -> Option<Ordering> {
Some(self.cmp(&other))
}
}
impl Ord for N {
fn cmp(&self, other: &N) -> Ordering {
self.0.cmp(&other.0).reverse()
}
}
fn main() {
let mut vec = vec!(N(2), N(1), N(3), N(5), N(4)); // randomized order
vec.sort();
let result = vec.binary_search(&N(5));
println!("{vec:?} {result:?}"); // output [N(1), N(2), N(3), N(4), N(5)] Err(0)
} The integers are sorted in descending order if you look at the values but the comparator sees them as being in "ascending order", so the sense used for "sorted" in the docs for |
Location
https://doc.rust-lang.org/std/primitive.slice.html#method.binary_search
Summary
Documentation states, that
but if we try to use binary search on something like
[5,4,3,2,1].binary_search(&5)
it will end up with error, though the slice is sorted in descending order.This either requires to fix docs to something like
or fix actual binary search algorithm by flipping direction of search in case left and right bounds are flipped.
The text was updated successfully, but these errors were encountered: