Hi,
I am working on a simple bubble sort program but I seem to have an error I understand it but I don't whats happening and where is it happening.
Full error:
$ cargo run
Compiling bubble_sort_rs v0.1.0 (D:\Programming\Algorithms\bubble_sort_rs)
warning: variable does not need to be mutable
--> src\main.rs:4:17
|
4 | fn bubble_sort (mut arr: Vec<i32> ) -> Vec<i32>{
| ----^^^
| |
| help: remove this `mut`
|
= note: `#[warn(unused_mut)]` on by default
warning: variable does not need to be mutable
--> src\main.rs:40:9
|
40 | let mut array = vec![9, 6, 3, 5, 1, 2];
| ----^^^^^
| |
| help: remove this `mut`
warning: 2 warnings emitted
Finished dev [unoptimized + debuginfo] target(s) in 0.85s
Running `target\debug\bubble_sort_rs.exe`
0
thread 'main' panicked at 'index out of bounds: the len is 6 but the index is 6', C:\Users\Ahmer Khan\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\core\src\slice\mod.rs:543:31
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
1error: process didn't exit successfully: `target\debug\bubble_sort_rs.exe` (exit code: 101)
My code:
// Main bubble sort
fn bubble_sort (mut arr: Vec<i32> ) -> Vec<i32>{
let mut a = arr;
let n = a.len();
for i in 0..n {
println!("{}",i);
for j in 1..(n-i-1) {
print!("{}",j);
if a[j] > a[j+1] {
// a[j] = a[j+1];
// a[j+1] = a[j];
let first = a[j];
let sec = a[&j+1];
a.swap(first as usize, sec as usize);
}
}
}
a
}
fn main() {
// defining vector
let mut array = vec![9, 6, 3, 5, 1, 2];
// Getting result
let res = bubble_sort(array);
// Processing the result
println!("{:?}",res);
}
Thanks in Advance ![]()