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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/// This module contains implementations of searching algorithms.
pub mod searching {
use std::collections::{HashSet, VecDeque};
/// Performs a linear search on a slice to find a target element.
///
/// This function iterates over the elements of the slice in order and compares each element
/// to the target element using the `PartialEq` trait. If a match is found, the index of the
/// matching element is returned.
///
/// # Arguments
///
/// * `arr` - A slice of elements to search through.
/// * `target` - The target element to search for.
///
/// # Returns
///
/// An `Option` containing the index of the target element if found, or `None` if the target
/// element is not present in the slice.
///
/// # Examples
///
/// ```
/// use algorithm_playground::algorithms::searching::searching::linear_search;
///
/// let arr = vec![1, 2, 3, 4, 5];
/// assert_eq!(linear_search(&arr, &3), Some(2));
/// ```
pub fn linear_search<T: PartialEq>(arr: &[T], target: &T) -> Option<usize> {
for (index, item) in arr.iter().enumerate() {
if item == target {
return Some(index)
}
}
None
}
/// Performs a binary search on a sorted slice to find a target element.
///
/// This function assumes that the slice is sorted in ascending order and uses the `Ord` trait
/// to compare elements. It repeatedly divides the search space in half until the target element
/// is found or the search space is exhausted.
///
/// # Arguments
///
/// * `arr` - A sorted slice of elements to search through.
/// * `target` - The target element to search for.
///
/// # Returns
///
/// An `Option` containing the index of the target element if found, or `None` if the target
/// element is not present in the slice.
///
/// # Examples
///
/// ```
/// use algorithm_playground::algorithms::searching::searching::binary_search;
///
/// let arr = vec![1, 2, 3, 4, 5];
/// assert_eq!(binary_search(&arr, &3), Some(2));
/// ```
pub fn binary_search<T: Ord>(arr: &[T], target: &T) -> Option<usize> {
let mut low = 0;
let mut high = arr.len() - 1;
while low <= high {
let mid = (low + high) / 2;
if arr[mid] == *target {
return Some(mid);
}
if arr[mid] < *target {
low = mid + 1;
} else {
high = mid - 1;
}
}
None
}
/// Example graph representation using an adjacency list
pub struct Graph {
pub edges: Vec<Vec<usize>>,
}
impl Graph {
/// Creates a new graph with the specified number of nodes.
///
/// # Arguments
///
/// * `num_nodes` - The number of nodes in the graph.
///
/// # Examples
///
/// ```
/// use algorithm_playground::algorithms::searching::searching::Graph;
///
/// let mut graph = Graph::new(5);
/// graph.add_edge(0, 1);
/// graph.add_edge(0, 2);
/// graph.add_edge(1, 3);
/// graph.add_edge(2, 4);
/// ```
pub fn new(num_nodes: usize) -> Self {
Graph {
edges: vec![vec![]; num_nodes],
}
}
/// Adds an undirected edge between two nodes.
///
/// # Arguments
///
/// * `from` - The index of the starting node.
/// * `to` - The index of the ending node.
///
/// # Examples
///
/// ```
/// use algorithm_playground::algorithms::searching::searching::Graph;
///
/// let mut graph = Graph::new(5);
/// graph.add_edge(0, 1);
/// graph.add_edge(0, 2);
/// graph.add_edge(1, 3);
/// graph.add_edge(2, 4);
/// ```
pub fn add_edge(&mut self, from: usize, to: usize) {
self.edges[from].push(to);
self.edges[to].push(from); // Assuming undirected graph
}
/// Performs a Depth-First Search (DFS) from the start node to find the target node.
///
/// Returns true if the target node is found, otherwise false.
///
/// # Arguments
///
/// * `start` - The index of the starting node.
/// * `target` - The index of the target node to search for.
///
/// # Complexity
///
/// The time complexity of DFS is O(V + E), where V is the number of vertices
/// and E is the number of edges in the graph.
///
/// # Examples
///
/// ```
/// use algorithm_playground::algorithms::searching::searching::Graph;
///
/// let mut graph = Graph::new(5);
/// graph.add_edge(0, 1);
/// graph.add_edge(0, 2);
/// graph.add_edge(1, 3);
/// graph.add_edge(2, 4);
/// assert!(graph.dfs(0, 4));
/// ```
pub fn dfs(&self, start: usize, target: usize) -> bool {
let mut visited = HashSet::new();
self.dfs_recursive(start, target, &mut visited)
}
pub fn dfs_recursive(&self, current: usize, target: usize, visited: &mut HashSet<usize>) -> bool {
if current == target {
return true;
}
if visited.contains(¤t) {
return false;
}
visited.insert(current);
for &neighbor in &self.edges[current] {
if self.dfs_recursive(neighbor, target, visited) {
return true;
}
}
false
}
/// Performs a Breadth-First Search (BFS) from the start node to find the target node.
///
/// Returns true if the target node is found, otherwise false.
///
/// # Arguments
///
/// * `start` - The index of the starting node.
/// * `target` - The index of the target node to search for.
///
/// # Complexity
///
/// The time complexity of BFS is O(V + E), where V is the number of vertices
/// and E is the number of edges in the graph.
///
/// # Examples
///
/// ```
/// use algorithm_playground::algorithms::searching::searching::Graph;
///
/// let mut graph = Graph::new(5);
/// graph.add_edge(0, 1);
/// graph.add_edge(0, 2);
/// graph.add_edge(1, 3);
/// graph.add_edge(2, 4);
/// assert!(graph.bfs(0, 4));
/// ```
pub fn bfs(&self, start: usize, target: usize) -> bool {
let mut visited = HashSet::new();
let mut queue = VecDeque::new();
queue.push_back(start);
while let Some(current) = queue.pop_front() {
if current == target {
return true;
}
if visited.contains(¤t) {
continue;
}
visited.insert(current);
for &neighbor in &self.edges[current] {
queue.push_back(neighbor);
}
}
false
}
}
/// Assuming a simple binary search tree structure
pub struct TreeNode<T> {
pub value: T,
pub left: Option<Box<TreeNode<T>>>,
pub right: Option<Box<TreeNode<T>>>,
}
impl<T: Ord> TreeNode<T> {
/// Creates a new tree node with the specified value.
///
/// # Arguments
///
/// * `value` - The value of the new tree node.
///
/// # Examples
///
/// ```
/// use algorithm_playground::algorithms::searching::searching::TreeNode;
///
/// let node = TreeNode::new(5);
/// ```
pub fn new(value: T) -> Self {
TreeNode {
value,
left: None,
right: None,
}
}
/// Checks if the tree contains a node with the specified value.
///
/// Returns true if the value is found, otherwise false.
///
/// # Arguments
///
/// * `target` - The value to search for in the tree.
///
/// # Complexity
///
/// The time complexity of contains method is O(log n) for balanced binary search trees,
/// where n is the number of nodes in the tree. However, it can degrade to O(n) for
/// unbalanced trees.
///
/// # Examples
///
/// ```
/// use algorithm_playground::algorithms::searching::searching::TreeNode;
///
/// let mut root = TreeNode::new(5);
/// let left_child = TreeNode::new(3);
/// let right_child = TreeNode::new(7);
/// root.left = Some(Box::new(left_child));
/// root.right = Some(Box::new(right_child));
///
/// assert!(root.contains(&3));
/// assert!(!root.contains(&4));
/// ```
pub fn contains(&self, target: &T) -> bool {
if *target == self.value {
return true;
}
if *target < self.value {
if let Some(ref left) = self.left {
return left.contains(target);
}
} else {
if let Some(ref right) = self.right {
return right.contains(target);
}
}
false
}
}
}