Rust Program to Implement Linear Search

Rust Program to Implement Linear Search

Linear Search is one of the simplest and most intuitive searching algorithms. It works by checking each element of a list or array, one by one, until it finds the target element or reaches the end of the list. This straightforward approach makes Linear Search a perfect starting point for beginners to understand basic search concepts and how algorithms operate on arrays.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Although Linear Search is not the most efficient method for large datasets, it is highly versatile and can be applied to unsorted data without any preparation. In Rust, implementing Linear Search also helps learners become familiar with loops, conditional statements, and array manipulation, all while reinforcing Rust’s ownership and safety principles.

Program 1: Linear Search Using a For Loop

This program demonstrates a basic Linear Search using a simple for loop to iterate over an array of integers.

fn linear_search(arr: &[i32], target: i32) -> Option<usize> {

    for (index, &value) in arr.iter().enumerate() {

        if value == target {
            return Some(index);
        }

    }

    None

}

fn main() {

    let numbers = [10, 23, 45, 70, 11, 15];
    let target = 70;

    println!("Array: {:?}", numbers);

    match linear_search(&numbers, target) {

        Some(index) => println!("Element {} found at index {}", target, index),
        None => println!("Element {} not found", target),

    }

}

In this program, each element is compared with the target value. If a match is found, the index is returned. Beginners can see clearly how iteration and conditional checks work together to find a value.

Program 2: Linear Search Using While Loop

Here, Linear Search is implemented with a while loop instead of a for loop. This approach helps beginners understand different looping constructs in Rust.

fn linear_search_while(arr: &[i32], target: i32) -> Option<usize> {

    let mut index = 0;

    while index < arr.len() {

        if arr[index] == target {
            return Some(index);
        }

        index += 1;

    }

    None

}

fn main() {

    let numbers = [3, 6, 9, 12, 15];
    let target = 12;

    println!("Array: {:?}", numbers);

    match linear_search_while(&numbers, target) {

        Some(idx) => println!("Element {} found at index {}", target, idx),
        None => println!("Element {} not found", target),

    }

}

This version helps beginners understand manual index management and looping control. It’s particularly useful when you need more control over iteration, such as skipping elements or early stopping.

Program 3: Linear Search Using Recursion

In this program, Linear Search is implemented recursively, which introduces learners to the concept of recursion while performing a simple search.

fn linear_search_recursive(arr: &[i32], target: i32, index: usize) -> Option<usize> {

    if index >= arr.len() {
        return None;
    }

    if arr[index] == target {
        return Some(index);
    }

    linear_search_recursive(arr, target, index + 1)

}

fn main() {

    let numbers = [5, 10, 15, 20, 25];
    let target = 15;

    println!("Array: {:?}", numbers);

    match linear_search_recursive(&numbers, target, 0) {

        Some(idx) => println!("Element {} found at index {}", target, idx),
        None => println!("Element {} not found", target),

    }

}

Recursion helps beginners understand how function calls can manage iteration implicitly. This approach is elegant but less memory-efficient for very large arrays due to the call stack.

Program 4: Linear Search for Strings

Linear Search isn’t limited to numbers. Here, it is applied to an array of strings to find a particular word.

fn linear_search_string(arr: &[&str], target: &str) -> Option<usize> {

    for (i, &word) in arr.iter().enumerate() {

        if word == target {
            return Some(i);
        }

    }

    None

}

fn main() {

    let words = ["rust", "python", "java", "go"];
    let target = "java";

    println!("Array: {:?}", words);

    match linear_search_string(&words, target) {

        Some(idx) => println!("Word '{}' found at index {}", target, idx),
        None => println!("Word '{}' not found", target),

    }

}

This example shows that Linear Search can be applied to any comparable type, broadening its usefulness for beginners learning about different data types.

Program 5: Linear Search with Debug Output

This version adds debug prints to show each comparison step, helping beginners visualize how Linear Search works internally.

fn linear_search_debug(arr: &[i32], target: i32) -> Option<usize> {

    for (index, &value) in arr.iter().enumerate() {

        println!("Checking index {}: value {}", index, value);

        if value == target {
            return Some(index);
        }

    }

    None

}

fn main() {

    let numbers = [8, 2, 5, 9, 3];
    let target = 5;

    println!("Array: {:?}", numbers);

    match linear_search_debug(&numbers, target) {
        Some(idx) => println!("Element {} found at index {}", target, idx),
        None => println!("Element {} not found", target),
    }

}

Debug output helps beginners see the step-by-step comparison, making the search process more tangible and easier to understand.

Frequently Asked Questions (FAQ)

Q1: What is the time complexity of Linear Search?
Linear Search has a worst-case and average-case complexity of O(n), where n is the number of elements. Best case is O(1) if the target is the first element.

Q2: Can Linear Search work on unsorted arrays?
Yes, Linear Search does not require the array to be sorted. It works on any array or list.

Q3: Is Linear Search efficient for large datasets?
No, for very large datasets, algorithms like Binary Search are much faster if the data is sorted.

Q4: Can Linear Search handle duplicates?
Yes, but it will return the first occurrence of the target. You can modify it to return all occurrences.

Q5: Why learn Linear Search if it is not efficient?
It is simple, easy to understand, and forms the foundation for learning more advanced search algorithms.

Conclusion

Linear Search is a simple yet essential algorithm for beginners in Rust and programming in general. By implementing it with loops, recursion, strings, and debug output, learners can understand the basics of searching, iteration, and array handling. Practicing Linear Search helps develop fundamental programming skills, preparing beginners for more complex search and sorting algorithms in Rust.

Scroll to Top