优先队列未保持排序顺序 [英] Priority queue is not maintaining sorting order

查看:63
本文介绍了优先队列未保持排序顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

优先级队列未保持排序顺序我是否无法正确实施Comparable?输出的排序顺序不正确?

Priority queue is not maintaining sorting order Am i implementing Comparable not properly? Wrong sorting order is coming as output?

import java.util.PriorityQueue;

    class A implements Comparable 
    {
        int i;
        A(int i)
        {
            this.i =  i;

        }
        public int compareTo(Object obj)
        {
            return i - ((A)obj).i;
        }
        public String toString()
        {
            return Integer.toString(i);
        }

    }
    class Manager11
    {
        public static void main(String[] args) 
        {
            PriorityQueue pq =  new PriorityQueue();
            pq.add(new A(9));
            pq.add(new A(5));
            pq.add(new A(8));
            pq.add(new A(19));
            pq.add(new A(1));

            System.out.println(pq);
        }
}

输出:[1、5、8、19、9]

Output : [1, 5, 8, 19, 9]

推荐答案

在优先级队列中,唯一的保证是 head 是最低的(或最大的,取决于您的比较).内部结构不一定是排序列表.实际上,在Java中,这是一个堆:

In a priority queue, the only guarantee you have is that the head is the lowest (or greatest, depending on your comparison). The internal structure is not necessarily a sorted list. Actually, in Java, it's a heap:

PriorityQueue

基于优先级堆的无界优先级队列.

An unbounded priority queue based on a priority heap.

但是,如果执行的循环是 poll()的第一项,则一次又一次地打印它,直到优先级队列为空.元素应从最小到最大打印.

However, if you do a loop that poll() the first item, then print it, again and again until the priority queue is empty. The elements should be printed from the lowest to the greatest element.

这篇关于优先队列未保持排序顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆