自定义比较器没有做足够的比较
Custom Comparator is not doing enough Comparison
我想根据以下标准对值进行排序:
如果 i 和 j 的值之和为奇数,则仅应交换值。输出字符串应按字典顺序尽可能小。
输入:1 2 5 3 8 10 32 51 5 8
输出:1 2 5 3 8 10 32 51 5 8
期望输出:1 2 5 3 5 10 32 8 8 51
我正在使用这段代码。但它没有给出预期的结果。
Collections.sort(list, new Comparator<Integer>()
{
public int compare(Integer a, Integer b) {
if ((a + b) % 2 != 0)
return a - b;
else
return 0;
}
});
你不能那样做。 Comparator.compare
的 documentation 表示
Finally, the implementor must ensure that compare(x, y) == 0 implies that sgn(compare(x, z)) == sgn(compare(y, z)) for all z.
但是你的Comparator
在x = 0
、y = 2
、z = 1
时不满足这个条件。
0 == 2
0 < 1
2 > 1
这不是您实施的问题,而是您尝试做的事情的问题。
我想根据以下标准对值进行排序: 如果 i 和 j 的值之和为奇数,则仅应交换值。输出字符串应按字典顺序尽可能小。
输入:1 2 5 3 8 10 32 51 5 8
输出:1 2 5 3 8 10 32 51 5 8
期望输出:1 2 5 3 5 10 32 8 8 51
我正在使用这段代码。但它没有给出预期的结果。
Collections.sort(list, new Comparator<Integer>()
{
public int compare(Integer a, Integer b) {
if ((a + b) % 2 != 0)
return a - b;
else
return 0;
}
});
你不能那样做。 Comparator.compare
的 documentation 表示
Finally, the implementor must ensure that compare(x, y) == 0 implies that sgn(compare(x, z)) == sgn(compare(y, z)) for all z.
但是你的Comparator
在x = 0
、y = 2
、z = 1
时不满足这个条件。
0 == 2
0 < 1
2 > 1
这不是您实施的问题,而是您尝试做的事情的问题。