diff --git a/solutions/rust/binary-search/2/Cargo.toml b/solutions/rust/binary-search/2/Cargo.toml new file mode 100644 index 0000000..f7721fb --- /dev/null +++ b/solutions/rust/binary-search/2/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "binary_search" +version = "0.1.0" +edition = "2024" + +# Not all libraries from crates.io are available in Exercism's test runner. +# The full list of available libraries is here: +# https://github.com/exercism/rust-test-runner/blob/main/local-registry/Cargo.toml +[dependencies] + +[features] +generic = [] + +[lints.clippy] +needless_borrows_for_generic_args = "allow" diff --git a/solutions/rust/binary-search/2/src/lib.rs b/solutions/rust/binary-search/2/src/lib.rs new file mode 100644 index 0000000..69a03bc --- /dev/null +++ b/solutions/rust/binary-search/2/src/lib.rs @@ -0,0 +1,24 @@ +use std::cmp::Ordering; + +pub fn find(array: impl AsRef<[T]>, key: T) -> Option { + match array.as_ref().len() { + 0 => None, + 1 => match array.as_ref().first().is_some_and(|item| *item == key) { + true => Some(0), + false => None, + }, + _ => { + let half = array.as_ref().len() / 2; + match array.as_ref().get(half) { + Some(item) => match item.partial_cmp(&key) { + Some(Ordering::Equal) => Some(half), + Some(Ordering::Greater) => find(array.as_ref().get(..half).unwrap(), key), + Some(Ordering::Less) => find(array.as_ref().get(half..).unwrap(), key) + .map(|next_idx| half + next_idx), + _ => None, + }, + _ => None, + } + } + } +}