Table of content

Linear Search in Rust

Linear search, also known as sequential search, is a way to find a target in a sequence. Just as literally, a linear search will iterate through the sequence, and the tenant will compare each element with the target value. If they are equal, stop iterating and return the search results.

At the beginning of the linear search, it is the simplest and most naïve implementation, and the performance should not be very good.

In fact, when the amount of data is small (less than 100 elements), the performance of linear search is not too bad, because other search algorithms may need to establish a special data structure, which will lead to a sudden increase in the initial space complexity.

/// Linear search.

pub fn linear_search<T>(arr: &[T], target: &T) -> Option<usize>
where T: PartialEq,
{ for (index, item) in arr.iter().enumerate() { if item == target { return Some(index); } } None }

mod base { use super::*;

base_cases!(linear_search); }

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions