The sort function works by looking at whether the value returned by the comparator function is negative or positive. Basically, if it's positive, it swaps the numbers. If it's negative or zero, it leaves them in that order. It keeps traversing the array until all pairs return a non-positive value.
In this case:
- 40-100 = -60 so leave those two alone. Array is [40, 100, 1, 5, 25, 10]
- 100-1 = 99 so swap. Array is [40, 1, 100, 5, 25, 10]
- 100-5 = 95 so swap. [40, 1, 5, 100, 25, 10]
- 100-25= 75 so swap. [40, 1, 5, 25, 100, 10]
- 100-10= 90 so swap. [40, 1, 5, 25, 10, 100]
- Start over. 40-1 = 39, so swap. [1, 40, 5, 25, 10, 100]
and so on... This is fairly inefficient, so it's likely that under the hood, something more efficient is going on, but for the purposes of predicting your output, this is sufficient.
You could write your sort function like this and get the same result:
function(a, b) {
if (a > b) return 1;
else if (a < b) return -1;
else return 0;
}
points.sort(function(a,b){return a-b});
part.function(a,b){return a-b}
.