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?