Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

213
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda