Does anyone have a useful mnemonic for implementing Comparator?
-
14-11-2019 - |
Question
Every time I need to implement a comparator, I get stuck trying to remember when I should return -1 and when 1, and I have to look it up.
I mean, obviously -1 is less, so it implies that first
is less than second
. But whenever I say that to myself, I get that nagging "are you sure?" feeling. I suspect part of my confusion comes from implementing it the other way around whenever I need a descending sort.
What do you use to remember which is which?
Solution
comparator.compare(a, b) < 0
<==> a < b
OTHER TIPS
I use this simple "substraction" mnemonic:
first - second
So, if first
is "less" than second
you'll get negative result, otherwise - positive or zero if they are equal.
I am not sure what you mean by mnemonic. However, I have had a very similar cognitive dissonance.
I am very visual, so I use the number line (the one I was taught in grade school). I just visualize the negative numbers as "left", 0 as "center" and positive numbers as "right". That the corresponds to the truth: -1 < 0 < 1
I remember the base integer case (pseudocode):
int comparator(int a, int b) {
return a-b;
}
So if we give in a small a
and a large b
which is the first < last we get a negative result.
I have a more visual memory, so remembering the "structure" of that function is easy and natural for me.