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

132
Visualizações
Sorting Array Elements with .sort()

I'd like to understand intrinsically, how does array.sort() method works? Like, under the hood, what happens? Is this a kind of data structure that works really fast? Is there a for.each hidden somewhere in the code because I can't figure out what happens with a and b

let numbers = [ 0, 1, 10, 2, 20, 3, 30 ];
numbers.sort((a,b) =>{
    if(a > b) return 1;
    if(a < b) return -1;
    return 0;
});

console.log(numbers);

Plus, how can the above code become this:

let numbers = [ 0, 1, 10, 2, 20, 3, 30 ];
numbers.sort((a, b) => a - b);
console.log(numbers);

#EDIT1 Ok, I got that if the result of a-b is negative a get first position, otherwise are swapped, if they are equal they stay in position. My question is: does Javascript engine sort every time till there is no more swapping?

Let's pretend I have  arr = [1,20,10,5,2] 
1st round: a=1 b=20 result  [1,20,10,5,2]
2nd round: a=10 b=20 result [1,10,20,5,2]
3rd round: a=20 b=5 result  [1,10,5,20,2]
end of this cycle becomes   [1,10,5,2,20] 

Array is not fully sorted. Does it start all over again? Where and how does the engine know that the sorting has finished?

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