Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logic behind reverse compare function in the array.sort() method

Tags:

javascript

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.

like image 377
codetalker Avatar asked Jan 07 '23 01:01

codetalker


1 Answers

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:

  • If your compare function returns 0, it doesn't matter what order the two should be in.
  • If your compare function returns less than 0 (it doesn't matter how far), the first argument should go before the second argument.
  • If your compare function returns greater than 0 (again, it doesn't matter how far), the second argument should go before the first argument.

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.

like image 157
TheHans255 Avatar answered Jan 09 '23 15:01

TheHans255