Index out of bounds with range and length of an array

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\
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\
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`
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\
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 {

        for j in 1..(n-i-1) {

            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);






fn main() {
    // defining vector
    let mut array = vec![9, 6, 3, 5, 1, 2];

    // Getting result
    let res = bubble_sort(array);

    // Processing the result


Thanks in Advance :slight_smile:

The problem here is that swap() takes the indices of the elements to swap, whereas you're passing in the elements themselves. The fact that it takes usize rather than i32 is an indication of that.

1 Like

Yeah, so you want this:

a.swap(j, j+1);

You're looking up values from inside the vector, and then using those as indices when you pass them to swap. 6 is one of your values and that's bigger than your largest vector index. Just give swap the indices you want to swap instead:

a.swap(j, j+1);

Your inner loop is also off by one. I suggest you apply the change to swap and try and solve the rest yourself before looking at the playground.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.