8000 Merge pull request #1232 from Priyansh2001here/dev · FoxMD/Algorithms@120aaef · GitHub
[go: up one dir, main page]

Skip to content

Commit 120aaef

Browse files
authored
Merge pull request VAR-solutions#1232 from Priyansh2001here/dev
Create linear_search.rs
2 parents 1b4c4c7 + 9e5c57f commit 120aaef

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
fn linear_search(v : &Vec<i32>, value : i32) -> i32{
2+
for (i, &j ) in v.iter().enumerate() {
3+
if j == value{
4+
return i as i32;
5+
}
6+
}
7+
return i32::MAX;
8+
}
9+
10+
11+
fn main() {
12+
println!("Hello, world!");
13+
let v : Vec<i32> = vec![1,2,3,4,5,9,0];
14+
let index = linear_search(&v, 4);
15+
if index != i32::MAX{
16+
println!("index of element is -> {}", index);
17+
}
18+
else {
19+
println!("Element not found");
20+
}
21+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
fn binary_search(v : &Vec<i32>, value : i32) -> i32{
2+
let mut low = 0;
3+
let mut high = v.len()-1;
4+
5+
while low <= high {
6+
7+
let mid = (low+high)/2;
8+
9+
if value > v[mid]{
10+
low = mid+1;
11+
}
12+
else if value < v[mid] {
13+
high = mid-1;
14+
}else {
15+
return mid as i32;
16+
}
17+
}
18+
i32::MAX
19+
}
20+
21+
22+
fn main() {
23+
let mut v: Vec<i32> = vec![1, 2, 3, 4, 5, 9, 0];
24+
v.sort();
25+
let index = binary_search(&v, 9);
26+
if index != i32::MAX{
27+
println!("index of element is -> {}", index);
28+
}
29+
else {
30+
println!("Element not found");
31+
}
32+
}

0 commit comments

Comments
 (0)
0