+ 3

How do I rearrange this queue after using the remove () method?

good afternoon can someone please explain to me why after deleting the first element in the queue (root of the binary tree) the element with priority 2 is in second place https://code.sololearn.com/cuso4KMOU6HY/?ref=app

24th May 2020, 4:31 PM
Alison Andrea
5 Respuestas
0
first out move next priority and order to free first place move last in queue to free place (order,priority): [(1,1)x (5,1), (7,1), (4,3), (2,3), (6,2), (3,2)] (5,1) (3,2) move here [(5,1)x (3,2), (7,1), (4,3), (2,3), (6,2)] (7,1) (6,2) move [(7,1)x (3,2), (6,2), (4,3), (2,3)] (3,2) (2,3) move [(3,2)x (2,3), (6,2), (4,3)] (6,2) (4,3) move [(6,2), (2,3), (4,3)]
25th May 2020, 12:10 AM
zemiak
+ 5
You can pass a Comparator as constructor argument to the PrioritizedQueue to keep the Queue sorted (it is an unordered Collection and can - but doesn't necessarily- keep the sorting order if you don't pass in a Comparator). Usually if you need an ordered collection you wouldn't use a queue. The queue is more for 'I don't care what the collection contains, just give me the thing that was in there for the longest time' (FIFO). Anyways, here's a short how to about Comparators if a sorted queue is really what you need: https://www.baeldung.com/java-comparator-comparable
24th May 2020, 5:36 PM
Tashi N
Tashi N - avatar
+ 5
You're comparing based on the value of the objects prioridad member. Integer.compare() returns 0 if equal Negative if x < y Positive if x > y PriorityQueue is a heap style structure and will sort the next smallest (given that the comparator returns a negative for the smaller number) to the top of the heap. The remaining items position in the heap is arbitrary. So each time remove() is called it "bubbles" the next, or one of the next, items to the top and once there the other items remain where they were moved to in that process.
24th May 2020, 5:58 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
Thanks Something that seems strange to me is that the last element (in this case "Pedro" with priority 2) level up and even take possession on the left side of the binary tree (which is how PriorityQueue is represented) because when "Jose" is as root after using the remove () method means that it was prioritized to be on the left side and its priority was not taken into account because both "Jose" and "Raul" had the same priority (1)
24th May 2020, 7:04 PM
Alison Andrea
0
Thank you!!!
25th May 2020, 12:15 AM
Alison Andrea