Skip to content

Commit

Permalink
chore: add search linear
Browse files Browse the repository at this point in the history
  • Loading branch information
0xBoji authored Jan 27, 2024
1 parent 7bdd680 commit 08b69da
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
28 changes: 28 additions & 0 deletions src/day07_to_day09/linear_search.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use std::io;

fn linear_search(arr: &[i32], x: i32) -> i32 {
for (index, &item) in arr.iter().enumerate() {
if item == x {
return index as i32;
}
}
}

pub fn run() {
let arr = [2, 3, 4, 10, 40];
println!("Nhập giá trị x cần tìm kếm:");

let mut x = String::new();
io::stdin().read_line(&mut x)
.expect("Lỗi khi đọc giá trị x");

let x: i32 = x.trim().parse()
.expect("Lỗi khi chuyển đổi giá trị x thành số");

let result = linear_search(&arr, x);
if result == -1 {
println!("Phần tử không tồn tại trong mảng");
} else {
println!("Phần tử được tìm thấy tại chỉ số: {}", result);
}
}
3 changes: 2 additions & 1 deletion src/day07_to_day09/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod fibonacci;
pub mod fibonacci;
pub mod linear_search;
6 changes: 4 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ pub mod day04_to_day06;

//Day 07 to day 09
pub mod day07_to_day09;
use day07_to_day09::fibonacci;
// use day07_to_day09::fibonacci;
use day07_to_day09::linear_search;



Expand Down Expand Up @@ -52,7 +53,8 @@ fn main() {
// shadowing::run();
// ownership::run();
// borrowing::run();
fibonacci::run();
// fibonacci::run();
linear_search::run();


}

0 comments on commit 08b69da

Please sign in to comment.