forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
linear search in rust (jainaman224#2950)
linear search in rust Linear search in rust
- Loading branch information
Showing
1 changed file
with
68 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
// Rust program for Linear Search | ||
use std::io; | ||
|
||
fn main() { | ||
println!(" Enter number of elements to be entered in the array "); | ||
let mut size = String::new(); | ||
|
||
io::stdin().read_line(&mut size).expect("failed to read input."); | ||
let size: usize = size.trim_end().parse().expect("invalid input"); | ||
let mut vector: Vec<usize> = Vec::with_capacity(size as usize); | ||
|
||
println!("Enter element to be searched " ); | ||
let mut element = usize::new(); | ||
|
||
println!("Enter elements of array "); | ||
let mut index = 0; | ||
|
||
// Enter values into vector | ||
while index < size { | ||
index += 1; | ||
// Note: Rust takes spaces as non-intergral value | ||
let mut temp_arr = String::new(); | ||
io::stdin().read_line(&mut temp_arr).expect("failed to read input."); | ||
let temp_arr: usize = temp_arr.trim_end().parse().expect("invalid input"); | ||
vector.push(temp_arr); | ||
} | ||
|
||
// Linear Search process | ||
let mut checkpoint = 0; | ||
for index in 0..size - 1 { | ||
if element == vector[index]{ | ||
checkpoint = 1; | ||
println!("Element is found at index "); | ||
println!("{:?}" , index + 1); | ||
} | ||
} | ||
|
||
if checkpoint == 0 { | ||
println!("Element is not found in the array "); | ||
} | ||
} | ||
/* | ||
TEST CASE | ||
INPUT | ||
Enter number of elements to be entered in the array | ||
3 | ||
Enter element to be searched | ||
2 | ||
Enter elements of array | ||
1 | ||
2 | ||
3 | ||
OUTPUT | ||
Element is found at index | ||
2 | ||
INPUT | ||
Enter number of elements to be entered in the array | ||
3 | ||
Enter element to be searched | ||
5 | ||
Enter elements of array | ||
1 | ||
2 | ||
3 | ||
OUTPUT | ||
Element is not found in the array | ||
*/ | ||
|