Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Non-lexicographical reverse order with Integers in max heap

Tags:

java

Collections.reverseOrder() comparator does lexicographical sorting when used with a max heap toArray function.

Example: 4, 35, 41 would print as 41, 4, 35.

What I want is for it to print as 41, 35, 4

PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
maxHeap.add(4);

//Prints [4]
System.out.println("MaxHeap:"+ Arrays.toString(maxHeap.toArray()));

maxHeap.add(35);

//Prints [35, 4]
System.out.println("MaxHeap:"+ Arrays.toString(maxHeap.toArray()));

maxHeap.add(41);

//Prints [41, 4, 35]
System.out.println("MaxHeap:"+ Arrays.toString(maxHeap.toArray()));
like image 938
yetion Avatar asked May 13 '20 06:05

yetion


1 Answers

The default comparator of an Integer is not lexicographical.

The problem is that the internal array used by an PriorityQueue (which is what toArray() returns) is not sorted.

To get the elements in the sorted order you need to call the poll() method in the PriorityQueue until there are no more elements. This how the PriorityQueue functions by definition.

like image 71
MaanooAk Avatar answered Nov 14 '22 01:11

MaanooAk