其他分享
首页 > 其他分享> > Rust——二分查找法

Rust——二分查找法

作者:互联网

实现一:循环

fn search<E: PartialOrd>(data: Vec<E>, target: E) -> i32 {
    let mut l: i32 = 0;
    // 左闭右开区间
    let mut r = data.len() as i32;
    while l < r {
        let mid = l + (r - l) / 2;
        if data[mid as usize] == target {
            return mid;
        }
        if data[mid as usize] < target {
            l = mid + 1;
        } else {
            r = mid
        }
    }
    return -1;
}

实现二:递归实现

// 二分查找
fn search<E: PartialOrd>(data: Vec<E>, target: E) -> i32 {
    recursion_search(&data, 0, data.len() as i32 - 1, target)
}

// 递归调用
fn recursion_search<E: PartialOrd>(data: &Vec<E>, l: i32, r: i32, target: E) -> i32 {
    if l > r {
        return -1;
    }
    // 避免溢出
    let mid = l + (r - l) / 2;
    if data[mid as usize] == target {
        return mid;
    }
    if data[mid as usize] < target { // 中间值小于目标,就在右边寻找
        recursion_search(data, mid + 1, r, target)
    } else { // 中间值大于目标,就在左边寻找
        // mid - 1,如果mid=0,-1使用usize就会溢出,所以参数使用i32
        recursion_search(data, l, mid - 1, target)
    }
}

#[cfg(test)]
mod tests {
    use crate::binary_search::search;

    #[test]
    fn it_works() {
        let data = vec![5];
        assert_eq!(search(data, -5), -1);
    }
}

标签:二分,search,target,i32,mid,查找,usize,data,Rust
来源: https://blog.csdn.net/comien/article/details/118273454