Rust实现线性搜索算法(Linear Search)


本文将使用Rust实现线性搜索算法(Linear Search);

线性搜索算法原理

线性搜索,就是从头找到尾;比如有一个数组,从该数组的第一个值开始找到结尾,依次判断是否与要寻找的值相等;

Rust实现线性搜索

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

fn main(){
    let index1 = linear_search(&"d", &vec!["a", "b", "c", "d", "e", "f"]);
    println!("{:?}",index1);

    let index2 = linear_search(&"6", &vec!["1", "2", "3", "4", "5", "6"]);
    println!("{:?}",index2);

    let index3 = linear_search(&"x", &vec!["a", "b", "c", "d", "e", "f"]);
    println!("{:?}",index3);
}

程序运行结果

Some(3)
Some(5)
None

如需转载,请注明出处;本文地址:https://www.perfcode.com/p/rust-linear-search.html