Java 优先队列问题

查看 170|回复 14
作者:yuanyuandeqiu   
这样一段程序:
public static void main(String[] args) {
int[] reward = new int[]{1, 4, 4, 6, 4};
Queue[I] q1 = new PriorityQueue();
Queue[I] q2 = new PriorityQueue((a, b) -> b - a);
for (int j : reward) {
q1.add(j);
}
for (int j : reward) {
q2.add(j);
}
System.out.println(q1);//[1, 4, 4, 6, 4]
System.out.println(q2);//[6, 4, 4, 1, 4]
}
请教各位,为什么会排序错误

int, reward, Queue, integer

Zakl21   
直接 print 不一定有序的,你试试 while true pop 打印
Nazz   
正确的姿势是:
while(q.len() >0) {
println(q.pop())
}
yuanyuandeqiu
OP
  
@Nazz
@Zakl21
感谢,那 debug 的时候是不是也是无序的
yuanyuandeqiu
OP
  
debug 的时候 q 的顺序和 System.out.println 打印出来的一致,这是为什么
Nazz   
好好看看数据结构基础吧
jamezee   
看下类的注释就知道了
An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. A priority queue does not permit null elements. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so may result in ClassCastException).
...
This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).
yuanyuandeqiu
OP
  
@Nazz
@jamezee
感谢
fengpan567   
while(q2.peek() != null) {
println(q.poll());
}
azusachino   
优先队列只保证最大 /小堆,不保证顺序; online challenge 挂了之后,一查才知道。。。
您需要登录后才可以回帖 登录 | 立即注册

返回顶部