Home > Net >  Correct bubble sort in JS doesn't do anything
Correct bubble sort in JS doesn't do anything

Time:11-29

The code just logs the same array. What seems to be wrong here? I'm using VS Code.

function bubbleSort(array) {
  for (let i = 0; i < array.length - 1; i  ) {
    for (let j = 0; j < array.length - 1 - i; j  ) {
      if (array[j] > array[j   1]) {
        [array[j], array[j   1] = array[j   1], array[j]];
      }
    }
  }
  return array;
}

let arr1 = [9, 4, 6, 4, 3];

console.log(bubbleSort(arr1));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

It should be:

[array[j], array[j   1]] = [array[j   1], array[j]];

instead of:

[array[j], array[j   1] = array[j   1], array[j]];

Pay close attention to where the square brackets begin and end.


Your current code:

  1. assigns one array index to itself
  2. creates an array with 3 elements
  3. and throws it away immediately

What you actually want is a destructuring assignment. (thanks to @Reyno for the link!)

CodePudding user response:

Javascript is not python, you can't assign 2 array values like you're doing, you need to go step by step with a temp to replace 2 values

function bubbleSort(array) {
    for (let i = 0; i < array.length - 1; i  ) {
      for (let j = 0; j < array.length - 1 - i; j  ) {
        if (array[j] > array[j   1]) {
            let temp = array[j] 
            array[j] = array[j   1]
            array[j   1] = temp
        }
      }
    }
    return array;
  }
  
  let arr1 = [9, 4, 6, 4, 3];
  
  console.log(bubbleSort(arr1));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related