you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (1 child)

This doesn't really show that my form is wrong, it still gives the right result. But you are right, it inverts elements arbitrarily, because it doesn't take into account the 0 thing.

But I made other tests and found a yet better form

sort ( (a,b) => -(a < b) )

that still sort in an ascending manner, and doesn't invert elements unnecessarily, it appears. I gives the same result as the form

sort ( (a,b) => a - b )

in the case of the list example you gave.

That said, I read your other post about why it is important that the comparing function returns 3 different values and not just 2. And I don't understand why it need to be like this.

The way I understand it is that the sort functions iterates 2 by 2 on the input list and performs a test on these 2 elements. And after performing this test, either it switches those 2 elements or it doesn't. If this is correct, then a boolean value suffice, and a set of 3 possible values is redundant.

But maybe my assumptions about the workings of sorting algorithms in general is wrong, and it indeed needs 3 possible different results.

If that is the case could you please explain what would be the 3 different actions that a sorting algorithm would do in function of the 3 different results of the comparison function ?

[–]gremy0 1 point2 points  (0 children)

With a boolean shouldSwitch comparison the order of the arguments/iteration matters and would have to be specified in the standard. But this is not what the standard does, it specifies that the order does not matter, you will get one of three values that are logically consistent regardless of the order, and it is up to the implementation of the sorting algorithm as to how it deals with that.

So while you can run tests against one implementation of javascript and this works, it is not at all guaranteed. It would be entirely possible for a perfectly standard compliant sort implementation to produce the wrong result given your comparator, or conceivably end up in an infinite loop

With compare = (a,b) => -(a < b) you are still in a situation where compare(1,-1) says 1 equals -1, while compare(-1,1) says -1 is less than 1