Linear Search Algorithm in Rust

1. Introduction

Linear Search is the simplest search algorithm and is sometimes referred to as a sequential search. It works by iterating over a collection, comparing each element to the target value until the desired element is found or the end of the collection is reached.

2. Implementation Steps

1. Start from the first element.

2. Compare the current element with the target value.

3. If they are equal, return the current index.

4. If not, move on to the next element.

5. If the end of the collection is reached without finding the target value, return an indication that it's not present.

3. Implementation in Rust Programming

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
}
fn main() {
    let numbers = [23, 57, 41, 95, 73, 13, 45, 7, 34];
    match linear_search(&numbers, &73) {
        Some(index) => println!("Found at index {}", index),
        None => println!("Not Found"),
    }
}

Output:

Found at index 4

Explanation:

1. The function linear_search is generic, meaning it can be used with any data type that implements the PartialEq trait, which provides the ability to be compared for equality.

2. Inside the function, we use an enumerate method that returns each item in the slice along with its index.

3. For each item, we compare it to the target using the == operator.

4. If the item is equal to the target, we return Some with the index of the item.

5. If the end of the slice is reached and the target hasn't been found, we return None.

6. In the main function, we demonstrate the usage of linear_search on an array of numbers, searching for the number 73.


Comments