aboutsummaryrefslogtreecommitdiff
path: root/rust/binary-search/src/lib.rs
diff options
context:
space:
mode:
Diffstat (limited to 'rust/binary-search/src/lib.rs')
-rw-r--r--rust/binary-search/src/lib.rs16
1 files changed, 16 insertions, 0 deletions
diff --git a/rust/binary-search/src/lib.rs b/rust/binary-search/src/lib.rs
new file mode 100644
index 0000000..dc80137
--- /dev/null
+++ b/rust/binary-search/src/lib.rs
@@ -0,0 +1,16 @@
1pub fn find<T: Ord, C: AsRef<[T]>>(array: C, key: T) -> Option<usize> {
2 let array = array.as_ref();
3 match array.len() {
4 0 => None,
5 1 => Some(0).filter(|_| array[0] == key),
6 n => {
7 let mid = n / 2;
8 let (a1, a2) = array.split_at(mid);
9 if key < array[mid] {
10 find(a1, key)
11 } else {
12 find(a2, key).map(|i| i + mid)
13 }
14 }
15 }
16}