Linear Search in Rust

In this article, we have present the implementation of Linear Search in Rust along with its implementation. We have presented the code to benchmark it as well.

To get the idea of Linear Search as a prerequisite, go through this article.

Table of contents:

  1. Implementation of Linear Search in Rust
  2. Explanation of Linear Search Rust code
  3. Benchmarking code for Linear Search in Rust

Let us get started with Linear Search in Rust.

Implementation of Linear Search in Rust

Following is the code for Linear Search in Rust Programming Language:

// Linear Search in Rust
// Part of iq.opengenus.org
fn linear_search<T: Ord + std::fmt::Debug>(vector: &[T], 
                search_item: T) -> Result<usize, usize> {
    for (position, search_item) in vector.iter().enumerate() {
        if *search_item == i {
            return Ok(position)
        }
    }
    // Element not found
    Err(0)
}

fn main() {
    let index = linear_search(&"OpenGenus", &vec!["Google", 
            "Microsoft", "OpenGenus", "Apple", "Facebook"]);
    println!("Position: {}", index);
}

Save the above code in a file named linear.rs and run it using the following command:

rustc linear.rs
./linear.sh

The output will be:

2

Explanation of Linear Search Rust code

In tha above implementation of Linear Search in Rust, note the following points:

  • The datatype of input in T (which can be i32, f32 and others). We have used the concept of template to make the code generic.

  • We are taking two inputs: vector (an array of datatype T) and search_item (the item of datatype T that is to be searched).

  • We are using a for loop in Rust to go through each element in vector which is made into an iterable form using vector.iter().enumerate().

  • We are returing Ok(position) as we have added support for debugging. If debugging is not used then, you can return position directly.

  • If the element is not found, then we are returning Err(-1). If debugging is not used then, you can return -1 directly.

Benchmarking code for Linear Search in Rust

To create a benchmark test code to test your Linear Search function in Rust, you can used the following code:

extern crate test;

#[cfg(test)]
mod tests {
 
    use super::*;
    use test::Bencher;

    #[bench]
    fn linear(b: &mut Bencher) {
        let v = (0..100000).filter(|&i| i % 5 != 0).collect::<Vec<usize>>();
        b.iter(|| assert_eq!(linear_search(&v, 8000), Err(6400)))
    }
}

With this article at OpenGenus, you must have a strong idea of implementing Linear Search in Rust. Enjoy.