插入排序算法会出现溢出错误

时间:2017-06-17 03:15:01

标签: rust overflow

尝试运行插入排序算法时,如下面的Rust 1.15所示。

fn main() {
    println!("The sorted set is now: {:?}", insertion_sort(vec![5,2,4,6,1,3]));
}

fn insertion_sort(set: Vec<i32>) -> Vec<i32> {
    let mut A = set.to_vec();
    for j in 1..set.len() {
        let key = A[j];
        let mut i = j - 1;
        while (i >= 0) && (A[i] > key) {
            A[i + 1] = A[i];
            i = i - 1;
        }
        A[i + 1] = key;
    }
    A
}

我收到错误:

thread 'main' panicked at 'attempt to subtract with overflow', insertion_sort.rs:12
note: Run with `RUST_BACKTRACE=1` for a backtrace

为什么在这里发生溢出以及问题如何得到缓解?

1 个答案:

答案 0 :(得分:2)

原因是你试图在0 - 1类型中计算usize,这是无符号的(非负)。这可能会导致Rust出错。

为什么usize?因为Rust期望长度和索引usize。您可以明确地将它们转换为签名的,例如isize

fn main() {
    println!("The sorted set is now: {:?}", insertion_sort(vec![5,2,4,6,1,3]));
}

fn insertion_sort(set: Vec<i32>) -> Vec<i32> {
    let mut A = set.to_vec();
    for j in 1..set.len() as isize {
        let key = A[j as usize];
        let mut i = j - 1;
        while (i >= 0) && (A[i as usize] > key) {
            A[(i + 1) as usize] = A[i as usize];
            i = i - 1;
        }
        A[(i + 1) as usize] = key;
    }
    A
}

我建议的另一个解决方案是避免负指数。在这种情况下,您可以使用i + 1代替i,如下所示:

fn main() {
    println!("The sorted set is now: {:?}", insertion_sort(vec![5,2,4,6,1,3]));
}

fn insertion_sort(set: Vec<i32>) -> Vec<i32> {
    let mut A = set.to_vec();
    for j in 1..set.len() {
        let key = A[j];
        let mut i = j;
        while (i > 0) && (A[i - 1] > key) {
            A[i] = A[i - 1];
            i = i - 1;
        }
        A[i] = key;
    }
    A
}