首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PriorityQueue(Java)排序算法的麻烦:为什么排序与排序的ArrayList不同?

PriorityQueue(Java)排序算法的麻烦:为什么排序与排序的ArrayList不同?
EN

Stack Overflow用户
提问于 2014-01-03 18:50:06
回答 2查看 636关注 0票数 0

我当时在研究赫夫曼。但是我发现PriorityQueue的排序算法是有问题的;它没有进行足够的比较!然后,我编写了一个简单的类来测试集合的排序和PriorityQueue的排序:

代码语言:javascript
复制
public class Student implements Comparable<Student>{

    String name;
    int score;
    int math;

    public Student(int score, int math, String name) {
       this.name = name;
       this.score = score;
       this.math = math;
    }

    public int compareTo(Student other) {
       if (this.score > other.score) {
           return -1;
       } else if (this.score < other.score) {
           return 1;
       } else {
           if (this.math > other.math) {
               return -1;
           } else {
               return 1;
           }
       }

       return 0;
   }

   public String toString() {
       return("[" + name + " has Score: " + score + "(Math: " + math + ")]");
   }
}

但我得到的结果如下(在控制台上):

代码语言:javascript
复制
Priority Queue::::::::::
[Jeremy Lin has Score: 2350(Math: 800)]
[Qian has Score: 2150(Math: 800)]
[PoorMath has Score: 2060(Math: 600)]
[Hui has Score: 1800(Math: 690)]
[Kaiyu has Score: 2060(Math: 800)]
[Chao has Score: 0(Math: 0)]

ArrayList sorted::::::::
[Jeremy Lin has Score: 2350(Math: 800)]
[Qian has Score: 2150(Math: 800)]
[Kaiyu has Score: 2060(Math: 800)]
[PoorMath has Score: 2060(Math: 600)]
[Hui has Score: 1800(Math: 690)]
[Chao has Score: 0(Math: 0)]

怎么解释这个?太棒了!

非常感谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-01-03 19:03:44

我想你可能对优先级队列的工作方式有一点误解.

PriorityQueue结构不能保证整个结构按任何特定的顺序排序。它只保证从顶部弹出的下一个元素将是最高优先级项。如果您查看PriorityQueue的API,它不允许随机访问PriorityQueue中的任何元素,它只允许访问下一个元素(非常像堆栈或队列结构)。

另一方面,ArrayList是一种允许随机访问的数据结构,所以在对其进行排序时,所有内部元素都是有序的。

因此,在您的示例中,结构都是正确的,因为它们都将Jeremy Lin显示为第一个条目。

如果您在PriorityQueue中做了类似的事情,您应该会看到与排序的ArrayList相同的顺序:

代码语言:javascript
复制
PriorityQueue<Student> pq;

//initialize PriorityQueue

while(pq.size() > 0)
{
   System.out.println(pq.poll());
}

我相信Java的PriorityQueue是基于标准的堆数据结构的。您可以在这里找到一些基本细节:结构)

票数 6
EN

Stack Overflow用户

发布于 2014-01-03 19:03:50

PriorityQueue不是一个排序的集合,它是一个有效地维护“最低”元素的集合。来自javadoc

对于指定的排序,此队列的头是最小的元素。如果多个元素被绑在最小的值上,那么头就是这些元素中的一个--领带是任意断的。队列检索操作轮询、删除、查看和元素访问队列顶部的元素。 方法iterator()中提供的Iterator不能保证以任何特定的顺序遍历优先级队列的元素。如果需要有序遍历,请考虑使用Arrays.sort(pq.toArray())。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20910696

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档