Search code examples
javasortingarraylistcomparecomparison

Custom Comparator is not doing enough Comparison


I want to sort values based on following criteria: If sum of values at i & j is odd then only values should be swapped. Output string should be lexicographically smallest possible.

Input: 1 2 5 3 8 10 32 51 5 8
Output: 1 2 5 3 8 10 32 51 5 8
Desired Output: 1 2 5 3 5 10 32 8 8 51

I'm using this piece of code. but it is not giving desired result.

Collections.sort(list, new Comparator<Integer>()
        {
            public int compare(Integer a, Integer b) {
                if ((a + b) % 2 != 0)
                    return a - b;
                else
               return 0;
            }
        });

Solution

  • You can't do that. The documentation for Comparator.compare says

    Finally, the implementor must ensure that compare(x, y) == 0 implies that sgn(compare(x, z)) == sgn(compare(y, z)) for all z.

    But your Comparator does not meet this condition when x = 0, y = 2, z = 1.

    0 == 2
    0 < 1
    2 > 1
    

    This is not a problem of your implementation, but of what you are trying to do.