gpt4 book ai didi

rust - 插入排序算法给出溢出错误

转载 作者:行者123 更新时间:2023-11-29 08:16:18 27 4
gpt4 key购买 nike

在 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

这里为什么会溢出,如何缓解?

最佳答案

原因是您尝试计算 usize 类型的 0 - 1,它是无符号的(非负数)。这可能会导致 Rust 出错。

为什么使用?因为 Rust 期望 usize 用于长度和索引。您可以将它们明确地转换为签名的或从签名的转换为例如大小

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
}

关于rust - 插入排序算法给出溢出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44600404/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com