Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

69
Visualizações
Correct bubble sort in JS doesn't do anything

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda