From 7d9fb075b069f254fc8c679ff5d624e632c6741d 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 20:09:06 +0000 Subject: [PATCH] [Sync Iteration] rust/binary-search/3 --- solutions/rust/binary-search/3/Cargo.toml | 15 +++++++++++++++ solutions/rust/binary-search/3/src/lib.rs | 12 ++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 solutions/rust/binary-search/3/Cargo.toml create mode 100644 solutions/rust/binary-search/3/src/lib.rs diff --git a/solutions/rust/binary-search/3/Cargo.toml b/solutions/rust/binary-search/3/Cargo.toml new file mode 100644 index 0000000..f7721fb --- /dev/null +++ b/solutions/rust/binary-search/3/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/3/src/lib.rs b/solutions/rust/binary-search/3/src/lib.rs new file mode 100644 index 0000000..a635cf7 --- /dev/null +++ b/solutions/rust/binary-search/3/src/lib.rs @@ -0,0 +1,12 @@ +use std::cmp::Ordering; + +pub fn find(array: impl AsRef<[T]>, key: T) -> Option { + let half = array.as_ref().len() / 2; + match key.cmp(array.as_ref().get(half)?) { + Ordering::Less => find(array.as_ref().get(..half).unwrap(), key), + Ordering::Equal => Some(half), + Ordering::Greater => { + find(array.as_ref().get(half + 1..).unwrap(), key).map(|i| half + i + 1) + } + } +}