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

156
Visualizações
Este bucle while para mi algoritmo de clasificación no parece salir, ¿por qué?

Estoy codificando en javascript y estoy tratando de hacer un algoritmo de clasificación, y mi ciclo while no parece salir, ¿alguien sabe por qué?

 let sort = true let length = 0 let i = 1 function multiSort(n) { length = n.length-1 while (sort=true) { sort = false if (n[i]>n[i+1]) { [n[i],n[i+1] = n[i+1],n[i]] i += 1 sort=true if (i = length) { i = 1 } console.log(i) } } return n } console.log("Final Product: ", multiSort([3,2,5,1,4]), " Iterations: ", i)

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

0

Tienes un par de problemas aquí.

Como se mencionó, está usando javascript incorrectamente. Debería dedicar algún tiempo a aprender cómo funcionan los operadores y las comparaciones. Usted puede leer acerca de ellos aquí. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#assignment_operators

  1. Su declaración while nunca será falsa.
  2. n[i+1] en su declaración de comparación puede no estar definido, por lo que será falso cuando no deba verificarse.

He reescrito su algoritmo usando un ciclo for en lugar de un ciclo while ya que obtenemos un iterador gratuito cuando configuramos el ciclo.

 // We keep track of the iterations outside of the function let iterations = 0 function multiSort(n) { iterations++ // We set sort to false, if our conditions are not met we won't need to keep sorting let sort = false // Loop through every item in the array for(let i = 0; i < n.length; i++) { let next = n[i+1] // If the current item is larger than the next swap their positions. We also have to check for undefined here since the end of the array can't compare to anything. if(n[i] > next && next !== undefined) { // Set sort to true since at least one item need to be sorted. This will not be set if all items in the array are in sequence. sort = true n[i+1] = n[i] n[i] = next } } // If we set sort to true re-run everything with the current array. if(sort) { multiSort(n) } // return the final array return n } console.log("Final Product: ", multiSort([3,2,5,1,4]), " Iterations: ", iterations)

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