【发布时间】:2015-04-27 18:22:09
【问题描述】:
导入 java.util.Comparator; 导入 java.util.PriorityQueue;
公共类 minMaxHeap {
static class PQsort implements Comparator<Integer> {
public int compare(Integer one, Integer two) {
return two - one;
}
}
public static void main(String[] args) {
int[] ia = { 1, 10, 5, 3, 4, 7, 6, 9, 8 };
PriorityQueue<Integer> pq1 = new PriorityQueue<Integer>();
// use offer() method to add elements to the PriorityQueue pq1
for (int x : ia) {
pq1.offer(x);
}
for(int num : pq1){
System.out.print(" " + num);
}
System.out.println("");
PQsort pqs = new PQsort();
PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>(10, pqs);
// In this particular case, we can simply use Collections.reverseOrder()
// instead of self-defined comparator
for (int x : ia) {
pq2.offer(x);
}
for(int num : pq2){
System.out.print(" " + num);
}
}
}
我有这样的代码。 在 java 中,我使用优先级队列来存储值数组。 当我尝试将它们一张一张打印出来时,我希望看到它们是按顺序打印的。如:1 3 4 5 6 7 8 9。 但是为什么我看到“1 3 5 8 4 7 6 10 9”?
当我通过提供另一个比较器来使用 reversedOrder 时。 结果也很奇怪,就是 “10 9 7 8 4 5 1 4” 这是为什么呢?
谢谢
【问题讨论】:
-
你的比较器是什么?
-
@CPerkins 抱歉。更正了我的代码。之前复制了错误的代码。
-
@BufBills 请修正格式。
标签: java