dsa/algorithms/
searching.rs

1/// Performs a linear search to find the index of a target value in an array.
2///
3/// This function iterates through each element in the array and compares it
4/// with the target. If a match is found, the index of the target element is returned.
5///
6/// # Arguments
7///
8/// * `array` - A reference to a slice of integers where the target value is searched.
9/// * `target` - The integer value to search for in the array.
10///
11/// # Returns
12///
13/// * `Some(usize)` - If the target is found, returns the index of the target in the array.
14/// * `None` - If the target is not found, returns `None`.
15///
16/// # Examples
17///
18/// ```
19/// use dsa::algorithms::searching::linear_search;
20/// 
21/// let array = [1, 2, 3, 4, 5];
22/// assert_eq!(linear_search(&array, 3), Some(2));
23/// assert_eq!(linear_search(&array, 6), None);
24pub fn linear_search(array: &[i32], target: i32) -> Option<usize> {
25    for i in 0..array.len() {
26        if array[i] == target {
27            return Some(i);
28        }
29    }
30    None
31}
32
33/// Performs a binary search to find the index of a target value in a sorted array.
34///
35/// This function assumes that the array is sorted in ascending order. It works by 
36/// repeatedly dividing the search interval in half. If the target is less than 
37/// the middle element, the search continues in the left half, and if the target 
38/// is greater, the search continues in the right half. This process continues 
39/// until the target is found or the search interval is empty.
40///
41/// # Arguments
42///
43/// * `array` - A reference to a sorted slice of integers where the target value is searched.
44/// * `target` - The integer value to search for in the array.
45///
46/// # Returns
47///
48/// * `Some(usize)` - If the target is found, returns the index of the target in the array.
49/// * `None` - If the target is not found, returns `None`.
50///
51/// # Examples
52///
53/// ```
54/// use dsa::algorithms::searching::binary_search;
55/// 
56/// let array = [1, 2, 3, 4, 5];
57/// assert_eq!(binary_search(&array, 3), Some(2));
58/// assert_eq!(binary_search(&array, 6), None);
59/// ```
60pub fn binary_search(array: &[i32], target: i32) -> Option<usize> {
61    let mut left = 0;
62    let mut right = array.len() - 1;
63    while left <= right {
64        let mid = (left + right) / 2;
65        if target < array[mid] {
66            right = mid - 1;
67        } else if target > array[mid] {
68            left = mid + 1;
69        } else {
70            return Some(mid);
71        }
72    }
73    None
74}