英文:
How does java comparator work internally?
问题
class Checker implements Comparator<Player> {
@Override
public int compare(Player p1, Player p2) {
if (p1.score == p2.score) {
return p1.name.compareTo(p2.name);
} else {
return p2.score - p1.score;
}
}
}
p2.score - p1.score 如何使得排序是降序的
而 p1.score - p2.score 则使得排序是升序的
正整数、负整数或零是如何影响返回值来进行对象排序的?内部是怎么运作的?
请帮忙解答,谢谢
英文:
class Checker implements Comparator<Player> {
@Override
public int compare(Player p1, Player p2) {
if (p1.score == p2.score) {
return p1.name.compareTo(p2.name);
} else {
return p2.score - p1.score;
}
}
}
how does p2.score - p1.score make it descend
while p1.score - p2.score makes is ascend
how does a positive or negative integer or zero return
sort the objects? whats going on internally
please help thanks
答案1
得分: 0
从 Comparator
的文档 中:
一个比较函数,对某些对象的集合施加完全排序。...
以及从 Comparator:compare
的文档 中:
...
返回:
负整数、零或正整数,具体取决于第一个参数小于、等于或大于第二个参数。
因此,Comparator
仅定义顺序。排序算法根据这些信息对数据结构进行实际排序。如果我们看一下例如 快速排序(Quicksort) 和 归并排序(Merge Sort) 的工作原理,我们会发现这些算法只需要知道某个元素 a
是小于、等于还是大于 b
,而这正是 Comparator
提供的信息(通过返回值 < 0
、= 0
或 > 0
)。
现在让我们解释一下为什么 a - b
使其按升序排序(让我们将这个 Comparator
命名为 asc
),而 b - a
使其按降序排序(让我们将这个 Comparator
命名为 desc
):我们需要针对这两个 Comparator
来考虑三种不同的情况。
首先,假设 a > b
。然后
a - b > 0
,因此a
相对于b
在asc
中更大b - a < 0
,因此a
相对于b
在desc
中更小
接下来,假设 a < b
。然后
a - b < 0
,因此a
相对于b
在asc
中更小b - a > 0
,因此a
相对于b
在desc
中更大
最后,假设 a == b
。然后 a - b == b - a == 0
,根据这两个 Comparator
,元素是“相等”的。
英文:
From the Comparator
's documentation:
> A comparison function, which imposes a total ordering on some collection of objects. ...
And from Comparator:compare
's documentation:
> ...
>
> Returns:
>
> a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
Thus, the Comparator
only defines the order. It is up to the sorting algorithm to use this information and actually sort the data structure. If we take a look how, e.g., Quicksort and Merge Sort work, we see that these algorithms only need to know whether some element a
is smaller, equal or larger than b
, which is the information that a Comparator
provides (by returning a value < 0
, = 0
or > 0
).
Now let us explain how a - b
makes it sort in ascending order (lets give this Comparator
the name asc
), while b - a
makes it sort in decreasing order ((lets give this Comparator
the name desc
): We have to look at three different cases for the two Comparator
s.
First, suppose that a > b
. Then
a - b > 0
, thusa
is "larger" thanb
according toasc
b - a < 0
, thusa
is "smaller" thanb
according todesc
Next, suppose that a < b
. Then
a - b < 0
thusa
is "smaller" thanb
according toasc
b - a > 0
, thusa
is "larger" thanb
according todesc
Finally, suppose that a == b
. Then a - b == b - a == 0
and the elements are "equal" according to both Comparator
s.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论