From a8f8bb6b4cabd1627e9520ab488c036589f047cf Mon Sep 17 00:00:00 2001 From: "exercism-solutions-syncer[bot]" <211797793+exercism-solutions-syncer[bot]@users.noreply.github.com> Date: Sat, 4 Apr 2026 19:44:02 +0000 Subject: [PATCH] [Sync Iteration] rust/binary-search/1 --- solutions/rust/binary-search/1/Cargo.toml | 15 ++++++++++++ solutions/rust/binary-search/1/src/lib.rs | 30 +++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 solutions/rust/binary-search/1/Cargo.toml create mode 100644 solutions/rust/binary-search/1/src/lib.rs diff --git a/solutions/rust/binary-search/1/Cargo.toml b/solutions/rust/binary-search/1/Cargo.toml new file mode 100644 index 0000000..f7721fb --- /dev/null +++ b/solutions/rust/binary-search/1/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/1/src/lib.rs b/solutions/rust/binary-search/1/src/lib.rs new file mode 100644 index 0000000..8a6628d --- /dev/null +++ b/solutions/rust/binary-search/1/src/lib.rs @@ -0,0 +1,30 @@ +use std::cmp::Ordering; + +pub fn find(array: impl AsRef<[T]>, key: T) -> Option { + match array.as_ref().len() { + 0 => None, + 1 => { + return match array.as_ref().get(0).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) => return Some(half), + Some(Ordering::Greater) => { + return find(array.as_ref().get(..half).unwrap(), key); + } + Some(Ordering::Less) => match find(array.as_ref().get(half..).unwrap(), key) { + Some(next_idx) => return Some(half + next_idx), + _ => None, + }, + _ => None, + }, + _ => None, + } + } + } +}