为什么我的Java PriorityQueue表现得很奇怪

时间:2013-11-25 02:47:40

标签: java heap priority-queue comparator

我打算使用PriorityQueue作为5个元素的最小堆,每个元素都是一个声明如下的元组:

 public class Tuple implements Comparator<Tuple> {
    public final int x;
    public final double y;

    public Tuple(int x, double y) {
        this.x = x;
        this.y = y;
    }

    public Tuple() {
        this.x = 0;
        this.y = 0;
    }

    @Override
    public int compare(Tuple o1, Tuple o2) {
        return (int) (o1.y - o2.y);
    }
}

然后,我将我的堆声明为

 PriorityQueue<Tuple> heap = new PriorityQueue<Tuple>(5, new Tuple());
 int capacity = 5;

然后,我使用以下代码添加元素:

 if (capacity != 0) {
            if (score > 0) {
                Tuple tmp = new Tuple(i, score);
                heap.add(tmp);
                capacity -= 1;
            }
        } else {
            if (score > heap.peek().y) {
                OutPutPriorityQueue(heap);
                Tuple tmp = new Tuple(i, score);
                heap.remove();
                heap.add(tmp);
                OutPutPriorityQueue(heap);
            }
        }

其中,score是在其他位置计算的doubleOutPutPriorityQueue声明如下:

 public void OutPutPriorityQueue(PriorityQueue<Tuple> heap){
    Tuple [] temp = new Tuple[5];
    for (int i=0;i<5;i++){
        temp[i] = heap.poll();
        System.out.print(temp[i].y+"\t");
    }
    System.out.println();
    for (int i=0; i<5; i++){
        heap.add(temp[i]);
    }
}

很抱歉我在这里列出了太多代码,但这是我第一次使用PriorityQueue,我不确定它出错的地方以及代码的逻辑应该足够简单。

然后我的问题是,我的函数OutPutPriorityQueue的输出,应该按照一个顺序打印元素,基本上以任意方式打印元素,这里有一些示例:

 0.5549890273805606 0.6479515952918626  0.8593378488473195  0.53232731034541    1.0
 1.0    0.8593378488473195  0.53232731034541    0.8593378488473195  0.6479515952918626
 1.0    0.6479515952918626  0.8593378488473195  0.53232731034541    0.8593378488473195
 0.8593378488473195 1.6093378488473196  0.53232731034541    0.8593378488473195  0.6479515952918626 
 0.8593378488473195 0.6479515952918626  0.8593378488473195  0.53232731034541    1.6093378488473196
 1.6093378488473196 1.28601715282334    0.53232731034541    0.8593378488473195  0.6479515952918626

这些数字难以阅读,但其行为可归纳如下:

  1. remove()add()删除头部一个,将第五个移到头部并在第二个位置插入一个新头部。
  2. 2n-1应与行2n完全相同,但它们不同。第二个(最新的一个)与第五个交换
  3. 似乎此队列中没有定义任何顺序,但我确实定义了compare()并将其传入。
  4. 我不知道为什么会这样,我希望有人可以帮助我 我是否正确使用compare()?或其他什么?

    非常感谢!!

1 个答案:

答案 0 :(得分:1)

没有深入了解队列的细节,我要做的第一件事就是改变比较器。远离演员并使用Double提供的比较器。

public static int compare(double d1, double d2)

从API:返回 - 如果d1在数值上等于d2,则返回值0;如果d1在数值上小于d2,则小于0的值;如果d1在数值上大于d2,则值大于0.

您所拥有的比较容易出错,因此投注可能会导致问题。

相关问题