Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added binary search #2

Merged
merged 1 commit into from Oct 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 13 additions & 4 deletions src/lib.rs
@@ -1,15 +1,24 @@

mod search;
mod sorting;

#[cfg(test)]
mod tests {

use super::*;
use sorting::bubble::*;
use sorting::bubble_sort;
#[test]
fn test_bubble() {
let mut num = [4,3,2,1];
let mut num = [4, 3, 2, 1];
bubble_sort(&mut num);
assert_eq!(num, [1,2,3,4])
assert_eq!(num, [1, 2, 3, 4])
}

use search::binary_search;
#[test]
fn test_binary_search() {
let test_arr = [1, 5, 6, 7, 22, 46, 76, 88, 96, 100];
for i in 0..test_arr.len() {
assert_eq!(i, binary_search(&test_arr, test_arr[i]).unwrap())
}
}
}
1 change: 1 addition & 0 deletions src/main.rs
@@ -1,4 +1,5 @@
mod sorting;
mod search;

fn main() {

Expand Down
19 changes: 19 additions & 0 deletions src/search/binary_search.rs
@@ -0,0 +1,19 @@
pub fn binary_search(arr: &[i32], target: i32) -> Option<usize> {
let mut low = 0;
let mut high = arr.len() as i32 - 1;
while low <= high {
let mid = (high + low) / 2;
let m_index = mid as usize;
let val = &arr[m_index];
if *val == target {
return Some(m_index);
}
if *val < target {
low = mid + 1
}
if *val > target {
high = mid - 1
}
}
None
}
2 changes: 2 additions & 0 deletions src/search/mod.rs
@@ -0,0 +1,2 @@
pub mod binary_search;
pub use binary_search::*;
1 change: 0 additions & 1 deletion src/sorting.rs

This file was deleted.

2 changes: 2 additions & 0 deletions src/sorting/mod.rs
@@ -0,0 +1,2 @@
pub mod bubble;
pub use bubble::*;