fn binary_search<T: Ord>(mut array: &[T], key: T) -> Option<T>
A more useful signature would have been fn binary_search<T: Ord>(mut array: &[T], key: T) -> Option<usize>
And then returning `Some(middle)` on the Equal match. Returning the value you were given or None would be better expressed as returning True/False to avoid the unnecessary copy.Good point! And if you're doing that, there's no reason to use slices. So I guess the only thing to learn from my code... is that slices do useful bookkeeping for problems similar to this, in the case that you don't care about the indices?
> Returning the value you were given or None would be better expressed as returning True/False to avoid the unnecessary copy.
Just because two values are equal, doesn't mean they're the same. Though my function signature was wonky, regardless.
Equal => return Some(key),
The article's implementations return the index, not the value being searched for as you've done here. Do slices give access to their underlying offset?Also the article manages a single branch per iteration. How well does this cmp / match perform in comparison?
They don't have to, you already have `middle` available, they can just return Some(middle)
And __s's comment does it best: use the standard library. And that's a nice implementation (despite the unsafe stuff), which tracks the basepoint and size to keep the arithmetic clean.