【问题标题】:sorting integers by a priority queue [duplicate]按优先级队列对整数进行排序[重复]
【发布时间】:2014-01-04 16:35:49
【问题描述】:

我想写一个程序,可以按优先队列排序项目

但是下面的代码不起作用,我不知道问题所在

有什么帮助吗? 提前感谢您的关注

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());    
        }   
}  

}  

输出是这样的:

1 3 2 14 9 5 124 22 111 12 30

【问题讨论】:

  • 这是在文档中指定的。 "返回一个包含此队列中所有元素的数组。这些元素没有特定顺序。"
  • 看来您的目标是按升序对整数集合进行排序。当有其他/更好的选择时,为什么需要使用PriorityQueue
  • 阅读 Javadoc 可以回答您的问题。

标签: java sorting priority-queue


【解决方案1】:

您实际上尝试做的是堆排序。但是你不能用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));

打印出来的

[1, 2, 3, 5, 9, 12, 14, 22, 30, 111, 124]

这是因为PriorityQueue 在您添加或删除元素以维护堆属性时重新排列自身。

【讨论】:

    猜你喜欢
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多