diff options
| author | Federico Igne <git@federicoigne.com> | 2021-01-02 17:58:32 +0000 |
|---|---|---|
| committer | Federico Igne <git@federicoigne.com> | 2021-11-03 18:55:08 +0000 |
| commit | e7e054e21fd530fa6873b7aedd1fc4d4cfe5eb29 (patch) | |
| tree | 66933e429dbcb0e0dff68cc23cd1ef9430f12eed /rust/binary-search/src/lib.rs | |
| parent | fdde4fcd039210d7378c3f31ec9372396b1464a9 (diff) | |
| download | exercism-e7e054e21fd530fa6873b7aedd1fc4d4cfe5eb29.tar.gz exercism-e7e054e21fd530fa6873b7aedd1fc4d4cfe5eb29.zip | |
[rust] Binary Search
Diffstat (limited to 'rust/binary-search/src/lib.rs')
| -rw-r--r-- | rust/binary-search/src/lib.rs | 16 |
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 @@ | |||
| 1 | pub 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 | } | ||
