Java 提姆排序违例
这个比较器方法有什么问题 我读过: 要明白,如果c1>c2,c2>c3,那么c1>c3。我相信这一点在上述情况下应该是正确的 getMaxCosine()返回介于0..1之间的值,第二个排序是根据卡片中文本的长度,越长排名越高Java 提姆排序违例,java,timsort,Java,Timsort,这个比较器方法有什么问题 我读过: 要明白,如果c1>c2,c2>c3,那么c1>c3。我相信这一点在上述情况下应该是正确的 getMaxCosine()返回介于0..1之间的值,第二个排序是根据卡片中文本的长度,越长排名越高 public int compare(Card c1, Card c2) { if (getMaxCosine(c1) > getMaxCosine(c2)) { return -1; } else if (getMaxCosine(c1
public int compare(Card c1, Card c2) {
if (getMaxCosine(c1) > getMaxCosine(c2)) {
return -1;
} else if (getMaxCosine(c1) == getMaxCosine(c2)) {
return getMatchingText(c1).length() >= getMatchingText(c2).length() ? -1 : 1;
} else {
return 1;
}
}
我认为您的问题在于
if
-else
块:
else if (getMaxCosine(c1) == getMaxCosine(c2)) {
return getMatchingText(c1).length() >= getMatchingText(c2).length() ? -1 : 1;
}
else if (getMaxCosine(c1) == getMaxCosine(c2)) {
if (getMatchingText(c1).length() == getMatchingText(c2).length()) return 0;
return getMatchingText(c1).length() > getMatchingText(c2).length() ? -1 : 1;
}
如果getMatchingText(c1).length()
等于getMatchingText(c2).length()
,则返回-1
。这会产生一种“不稳定”排序:换句话说,排序后两个值相等的对象的顺序将颠倒。此外,对于在此比较器下相等的卡
s,应返回0。我建议在此if
-else
块中将=
比较更改为仅
:
else if (getMaxCosine(c1) == getMaxCosine(c2)) {
return getMatchingText(c1).length() >= getMatchingText(c2).length() ? -1 : 1;
}
else if (getMaxCosine(c1) == getMaxCosine(c2)) {
if (getMatchingText(c1).length() == getMatchingText(c2).length()) return 0;
return getMatchingText(c1).length() > getMatchingText(c2).length() ? -1 : 1;
}
如果c1和c2具有相同的最大余弦和相同的匹配文本长度,结果应该是什么?实际结果是什么?请注意,您的比较器可以通过简单地使用
比较器来简化(和固定)。comparingDouble(this::getMaxCosine)。然后comparingint(c->c.getMatchingText(c.length)
。Hi@jb nizet,Thx-我是否应该将“else if”块更改为类似的内容:else if(getMaxCosine(c1)=getMaxCosine(c2)){if(getMatchingText(c1.length()>getMatchingText(c2.length())返回-1;else if(getMatchingText(c1.length()
在这种情况下,卡片应该相等:好,那么比较()方法返回,根据Comparator的javadoc,当两张卡相等时?它实际返回什么?提示:compare(card,card)
应该为card
的任何值返回0。它不会。我会让这更简单:返回整数。比较(getMatchingText(c2).length(),getMatchingText(c1).length())
感谢@ChocolateAndCheese的解释和解决方案!我想我已经接近它了,让我更新我的代码并尝试一下。感谢@everyone的响应,这真是stack overflow社区的巨大支持!