I am having trouble understanding the Sorting using a Custom Comparator in Java.
Queue<Integer> q = new PriorityQueue<>(arr.length, (a,b) -> ab);
gives me ascending order sort, while
Queue<Integer> q = new PriorityQueue<>(arr.length, (a,b) -> ba);
gives me a descending order sort.
What I can not understand is how is this working? Is b
the incoming element and a
already in the array or vice versa? Also, how is the ascending or descending order obtained?
If ab > 0
, this means that a>b
, so shouldn't b
be infront of a
in ascending order?
Comparison-based sorts distinguish values by determining whether or not they are <
, =
, or >
.
For example, 3 < 4
, 4 = 4
, 4 > 3
.
Java Comparators use the convention that
cmp(a, b) < 0
means a < b
cmp(a, b) = 0
means a = b
cmp(a, b) > 0
means a > b
Note that this means if cmp(x, y) = x - y
, then you get the normal ordering for the integers. You can check yourself that cmp(x, y) = -(x- y) = y - x
gives you the reverse ordering.
When sorting (or doing something else that moves generic elements around by their order, like a PriorityQueue), the algorithm will (repeatedly) consult the comparator to determine whether or not values it has been given are <
, =
, or >
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.