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

602
Visualizações
Why does compare function of sort() work like that?

I've read in documentation about compare function's work. This callback function can have 2 parameters. There are 3 "if" for them:

  • If compareFunction(a, b) returns a value > than 0, sort b before a.
  • If compareFunction(a, b) returns a value < than 0, sort a before b.
  • If compareFunction(a, b) returns 0, a and b are considered equal.

So, as far as I see, if compare function returns a value less than zero, compare algorithm do nothing (a and b stay in the same places). And if this function returns a value more than zero, a and b switches (b goes first).

Okay, that's understandable. But why my code below works like that?

let arr1 = [9, 3, 6, 7, 1];
console.log(arr1.sort((a, b) => 1)); //1 > 0 -> compare function should switch elements

let arr2 = [9, 3, 6, 7, 1];
console.log(arr2.sort((a, b) => -1)); //-1 < 0 -> compare function shouldn't switch elements

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

0

Your interpreation of the docs is wrong.

You say

-1 means elements should stay in the same place.

That's wrong, the docs just state that -1 means a should be sorted before b.

Depending on the underlying sorting algorithm, there is no guarantee whatsoever that, when calling the comparefunction with parameters a and b that a is currently before b in the array. Ie imagine an array [1,2,3]. It may be possible that the compare function is called with parameters (3, 1) or (1,3). But if you return -1 in the first case, 1 and 3 will indeed switch positions. And vice versa, if you return 1 in the second case, 1 and 3 will again switch places.

EDIT

Different browser implement sort differently. For instance if you execute the following snippet in chrome and in firefox you will get different results.

var arr = [1,2,3,4,5,6,7,8,9];
arr.sort((a,b) => {
    console.log(`${a}  ${b}`);
  return 1;
})
console.log(arr);

For instance in my current chrome (Version 94.0.4606.61 on Windows), b will be less than a for all calls of the compare function, and thus returning 1 from the compare function would mean, to sort b before a which is already the case. Thus nothing will change.

Wheras in my firefox (Version 92.0 on Windows) b will be greater than a for all calls of the compare function. And thus, returning 1 from the compare function would again mean to sort b before a, which is not currently the case. Thus, the array will be reversed ...

Other runtimes with again a different implementation of sort may again lead to other totally unpredictable results ...

about 4 years ago · Juan Pablo Isaza Relatório

0

If the compare function returns the wrong answer when asked the fundamental question which value is less than the other, why wouldn't you expect the wrong answer from the function that depends on it?

The sort algorithm probably makes the equivalent of two passes before it is done, and ends up returning the values back to its place on the second pass.

I say equivalent - it might be going through once, but on the lower index elements it sorts it one way, and on the higher elements it goes the other way.

For the second case, it considers the top elements sorted, and then the bottom elements it thinks it has to switch.

But sorts all work differently. A merge sort might depend on how many times it is divisible by 2. A quick sort might depend on the pivot position. An insertion sort might depend on number of elements being even or odd.

So philosophy aside, the fundamental issue is the following:

compare(1, 2) = 1, so switch.
compare(2, 1) = 1, so switch.

If you wanted a reason your bad compare function made sort behave the way it did, that is why.

If you actually wanted it to reverse the sort, then you want something like:

function compare(int a, int b)
{
  if (a < b) return 1;
  if (a > b) return -1;
  return 0;
}
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