When trying to run the insertion sort algorithm as shown below in 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
}
I get the error:
thread 'main' panicked at 'attempt to subtract with overflow', insertion_sort.rs:12
note: Run with `RUST_BACKTRACE=1` for a backtrace
Why does an overflow happen here and how is the problem alleviated?