forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinary_Search.rs
88 lines (72 loc) · 3.07 KB
/
Binary_Search.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Rust program for Binary 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 in a sorted 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);
}
// Binary Search process
let mut leftpart = 0;
let mut rightpart = size - 1;
let mut midindex = 0;
let mut checkpoint = 0;
while leftpart <= rightpart {
midindex = leftpart + (rightpart - leftpart) / 2;
// Element found
if vector[midindex] == element{
checkpoint = 1;
println!("Element is found at index ");
println!("{:?}" , midindex + 1);
break;
}
else if vector[midindex] < element{
leftpart = midindex + 1;
}
else {
rightpart = midindex - 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 in a sorted 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 in a sorted array
1
2
3
OUTPUT
Element is not found in the array
*/