I want to know how exactly JavaScript performs its sort()
algorithm in detail.
In the given code below, if a - b
is a negative number, a
comes before b
. If it is a positive number, b
comes before a
. And if it is equal it should remain unchanged.
exampleArray.sort((a, b) => a - b);
Now if we are to do that algorithm once in this array,
[0, 2, 1, 3, 1]
It should return this, right?
[0, 1, 2, 1, 3]
A detailed step by step of how I think it is done:
// Array
[0, 2, 1, 3, 1]
// a = 0 and b = 2 is negative, a comes before b
[0, 2, 1, 3, 1]
// a = 2 and b = 1 is positive, b comes before a
[0, 1, 2, 3, 1]
// a = 2 and b = 3 is negative, a comes before b
[0, 1, 2, 3, 1]
// a = 3 and b = 1 is positive, b comes before a
[0, 1, 2, 1, 3]
Unless we will do it many times, we should be able to get the right value which is this one.
[0, 1, 1, 2, 3]
How does JavaScript sort algorithm do it? Does it run the loop based on the amount of elements in the array?