在Java中实现Comparable的堆

时间:2014-12-06 21:49:50

标签: java

我有一个充满双打的数组,我想将这些双打保存在堆中。 问题是我需要记录数组的索引。

Double[] array = new Double[n]; //imagine it's filled with doubles

现在我有一个PriorityQueue:

PriorityQueue<Integer> heap = new PriorityQueue<Integer>(); //Integer because it's an heap of indexes

我想将数组的每个元素添加到堆中,但我想保留INDEX的记录。 所以想象一下我将索引0添加到堆中:

The heap stores 0, but uses array[0] to compare and sort it.
Not index 0 itself, that's just like a class index. Stores v but compares v.value

当我从堆中获取值时:

Imagine I do heap.pull();
The heap returns me index 0, and then I will know the value is array[0].

我能用可比较的方法做到这一点吗?

1 个答案:

答案 0 :(得分:0)

我希望我能理解你的问题。尝试运行下面的示例。看看你是否理解它,以及这是你正在寻找的行为。

int n = 10;
final double[] arr = new double[n];
for (int i = 0; i < n; ++i) {
    arr[i] = Math.random() * 100;
}
PriorityQueue<Integer> queue = new PriorityQueue<>(n, new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return (int) (arr[o1] - arr[o2]);
    }
});

for (int i = 0; i < n; ++i) {
    queue.add(i);
}

System.out.println(Arrays.toString(arr));
System.out.println(queue.toString());

请注意,当您向OutOfBoundsException添加意外内容时,这可能会非常快速地导致PriorityQueue