0

I don't think (hope) this one is another of those thousands of trivial Array.sort questions (wrong data types basically).

So what I'm trying to do is:

[1, 3, 2, 7, 9, 4].sort((a, b) => a % 2 === 0 && b % 2 === 0 ? b - a : a - b)

that is, pairs of even numbers are to be ordered in descending order, the rest in ascending order as usual.

What I get is

[1, 2, 3, 4, 7, 9]

which is no surprise as only these pairs are compared:

[1, 3]
[3, 2]
[1, 2]
[3, 7]
[7, 9]
[9, 4]
[7, 4]
[3, 4]

So 2 and 4 are never compared to each other. Thus only one of my comparing rules is actually met in the result. What am I missing?

This is the result I'm expecting:

[1, 3, 4, 7, 9, 2]
DonFuchs
  • 133
  • 7
  • What result are you expecting? – Baboo Apr 01 '20 at 19:02
  • 3
    if `a < b` and `b < c`, then `a < c` so it doesn't need to compare them. – Barmar Apr 01 '20 at 19:02
  • You cannot use `sort` to create "pairs". Items need to be comparable individually. – Bergi Apr 01 '20 at 19:04
  • Okay, so my "rule" is not transitive which sort is expecting it to be? – DonFuchs Apr 01 '20 at 19:06
  • Added expected result to question btw – DonFuchs Apr 01 '20 at 19:07
  • 2
    @DonFuchs Exactly. If `a` is even and `b` is odd (or the other way round), you have [no good rule](https://stackoverflow.com/a/24080786/1048572). – Bergi Apr 01 '20 at 19:07
  • 1
    Your sort function is nondeterministic - the resulting order depends on exactly which pairs the JS engine chooses to compare, and in which order. Since you can't rely on a particular implementation, you should only use functions which genuinely compare the two values in a consistent way. In particular, the relation must be "transitive", which is the rule @Barmar mentions. – Robin Zigmond Apr 01 '20 at 19:08
  • Ok. But still my rule implies a unique order on the elements, mathematically it is consistent and well-defined. Is there any sorting method that doesn't assume transitivity? – DonFuchs Apr 01 '20 at 19:09
  • 1
    You can try maintaining two arrays; one for odd numbers and one for even; then iterate through your input array and populate the evens and odds arrays as necessary; finally sort them as required. Of course, it will lead to duplication of values of over arrays and not an inplace sort like you are attempting. – Abrar Hossain Apr 01 '20 at 19:11
  • 2
    Sorting algorithms generally try to avoid comparing every pair of elements, since that would be O(N^2). – Barmar Apr 01 '20 at 19:12
  • 2
    @DonFuchs No, it is not consistent. It says 3 > 2 and 2 > 1, but 1 > 3. Your rule is not a [partial order](https://en.wikipedia.org/wiki/Partially_ordered_set) – Bergi Apr 01 '20 at 19:16

0 Answers0