Though he brings up good points, it looks like @leonardo was too busy nitpicking the formatting and code style to notice the actual error–which is actually plain as day, at least by my eyes (and it’s almost bedtime for me).
The error message is a bit misleading, as we’re actually looking at an arithmetic underflow (unsigned value going under 0 and wrapping around to an absurdly high value), which is only triggered if the first two elements are out of order.
pub fn insertion_sort(arr: &mut[i32]) ->&mut [i32]{
let mut i =1;
let mut j =1;
let mut key: i32=0;
let mut arr_len = arr.len();
for i in 1..arr_len{
key = arr[i];
// On first iteration, this is set to 0
j = i-1;
while j>= 0 && key < arr[j] {
arr[j+1] = arr[j];
// If this is executed when j = 0, it will underflow.
j = j-1;
}
arr[j + 1] = key;
}
arr
}
This is triggered with a trivial test-case:
fn main() {
let mut array = [20, 10];
insertion_sort(&mut array);
}
Unfortunately, I’m a little too tired to go through and fix your sort implementation for you, but hopefully you at least know what’s going wrong now. 