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

212
Visualizações
Would this be a proper implementation of selection sort in javascript

Would the code below be the appropriate of implementing selection sort in Javascript?

let array = [24,27,43,11,32,7]; 
let temp; 

for(i = 0; i<array.length; i++){
    for(j =0; j<array.length; j++){
        if(array[i] < array[j]){
            temp = array[i]; 
            array[i] = array[j]; 
            array[j] = temp; 
        }
    }
}

console.log(array); 

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

0

No.

With selection sort, you build up the sorted segment on the left side of the array in pieces by swapping the lowest value from the unsorted section with the next unsorted index. For an array of length N, there should be only N swaps - your approach is swapping many more times because it's not breaking to the next i after a swap. You also aren't identifying the lowest value in the unsorted section.

In the nested loop (over j), you should

  • Start at the current value of i, not at 0 (because the portion of the array from 0 to i should already be sorted)
  • Identify the index of the lowest value in the segment from j to the end of the array - this could be done with Math.min followed by indexOf, or by saving a variable of the lowest value found so far as well as its index, or with many other ways
  • Swap that index with the i index, then break so as to go onto the next iteration of i

That said - if this is anything other than an algorithm exercise, I'd highly recommend using the built-in Array.prototype.sort method for sorting an array; it's more concise, makes more sense at a glance, and is far faster.

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