我想编写一个程序,可以按优先级队列对项目进行排序
但是下面的代码不起作用,我不知道问题
任何帮助?提前感谢您的关注
public class SortingASequenceByPriorityQueue {
public static void main(String[] args) {
PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>(1000, new Comparator<Integer>() {
public int compare(Integer w1, Integer w2) {
if(w1.intValue()> w2.intValue())
return 1;
else if( w1.intValue()< w2.intValue())
return -1;
return 0;
}
});
pQueue.add(12);
pQueue.add(1);
pQueue.add(5);
pQueue.add(22);
pQueue.add(3);
pQueue.add(2);
pQueue.add(124);
pQueue.add(14);
pQueue.add(111);
pQueue.add(9);
pQueue.add(30);
Object[] ar = pQueue.toArray();
for (int i = 0; i< ar.length; i++){
System.out.println(ar[i].toString());
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出是这样的:
1 3 2 14 9 5 124 22 111 12 30
你有效地尝试做的是堆排序.但你不能这样做toArray(),因为PriorityQueue,州
返回包含此队列中所有元素的数组.这些要素没有特别的顺序.
你要做的是逐个删除元素PriorityQueue并将它们添加到某个数组中.
Object[] arr = new Object[pQueue.size()];
for (int i = 0; i < arr.length; i++) {
arr[i] = pQueue.remove();
}
System.out.println(Arrays.toString(arr));
Run Code Online (Sandbox Code Playgroud)
打印
[1, 2, 3, 5, 9, 12, 14, 22, 30, 111, 124]
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为在PriorityQueue添加或删除元素以维护堆属性时会重新排列.