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

102
Visualizações
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 à 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