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

119
Vistas
How to make this javascript ordering consecutive integers ascending by swaps function more efficient?

Object is to order ascending an unordered list of consecutive integers 1,2,3.....n by swapping numbers (say swapping values at indices 3 and 6), and find the minimum number of swaps needed. My code works, but times out (10 second limit) when given the edge case 100000 integers. How can I streamline this code? To me it feels fairly minimal already - no nested loops or anything. I'm not very experienced with efficiency evaluation, any help would be appreciated, thanks.

function minimumSwaps(arr) {
    var swaps = 0;
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] !== i+1) {
            var tempIndex = arr.indexOf(i+1);
            var tempVal = arr[i];
            arr[i] = i+1;
            arr[tempIndex] = tempVal;
            swaps += 1;
    }
  }
  //console.log(swaps)
  return swaps;
}
about 4 years ago · Juan Pablo Isaza
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