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

90
Vistas
Why does javascript sort on arrays make different amounts of comparisons?
var arr=[..."12345678"]
var res=[];
var cnt=0;
function comparefn(a,b,c){
  var rnd1;
  console.log(`a=${a} , b=${b} , arr=${arr}`)
rnd1=Math.random() - 0.5;
  res.push(`${++cnt}) (${rnd1}) ${a},${b}` )
  
  
  return rnd1;
}

console.log(arr.sort(comparefn));

console.log(res.join(", "))

If I change the return value on the compare function (comparefn) then if it was a return of 1 then it would compare 28 times. If the return value of the compare function (comparefn) is 0 (zero) then is only compares it 7 times. Now, if the return value is Math.random() - 0.5 then it compare a variable number of times, from about 7 to 28 (which I suppose is the maximum number of 2 item permutations)? Some strange bits - on MDN is says 'Note: compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. ' I am not sure why it says that, because this function returns a random number (-1 to plus 1 approx) for ANY 2 items. As you may know this is the algo for the quick shuffle on an array (Math.random() - 0.5). I have found though, with 8 items that 0.3 gives a more natural order of items, that is to say that 0.5 used to favour the low numbers being in the start of the array but with 0.3 the array used to start with more different numbers - of course this is just by my eye (it could just be with eight items).

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

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