Now I know this will be a stupid question to many, but I cannot understand this logic. So, here is the problem in short:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
Now suppose, values 40 and 100 are compared, so the compare function returns a negative value, i.e -60. So, 40 is placed before 100. Understood.
Now, I do this:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
Again, if 100 and 40 are compared, the compare function returns a positive value, i.e 60. Now, shouldn't it place 100 after 40 because of that positive returned value? But it doesn't, and I am not getting that.
I just want to know what is happening here.
Your compare functions are exactly correct - you are using subtraction, which is very fast compared to branching and is in fact what a typical processor does when comparing two integer values. Essentially:
This last bit was where you got confused in your logic - in your head, you flipped both the order of the values and changed "before" to "after", which brings the statement right back to the first one again. :) Remember - the names of the parameters or whatever happens to them in the function does not matter - it is simply the order they come in the function arguments and the corresponding result returns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With