使用最小堆实现优先级队列

时间:2014-11-01 18:25:33

标签: java priority-queue min-heap

我正在尝试使用minheap实现优先级队列,但是我的对象以错误的顺序从队列中出来。我的直觉告诉我问题在于我在队列中进行筛选的方法,但我无法看到问题所在。有人可以查看我的算法,看看是否有任何错误立即显现?提前谢谢。

以下是筛选的方法:

private void walkDown(int i) {

    if (outOfBounds(i))
    {
        throw new IndexOutOfBoundsException("Index not in heap : " + i);
    }

    int current = i;
    boolean right;
    Customer temp = this.heap[i];

    while (current < (this.size >>> 1)) 
    {

        right = false;

        if (right(current) < this.size && 
                 this.comparator.compare(this.heap[left(current)],
                        this.heap[right(current)]) > 0)
        {
            right = true;
        }


        if (this.comparator.compare(temp, right ? this.heap[right(current)] 
                : this.heap[left(current)]) < 0)
        {
            break;
        }

        current = right ? right(current) : left(current);
        this.heap[parent(current)] = this.heap[current];

    } 

    this.heap[current] = temp;

}

筛选的方法:

private void walkUp(int i) {

    if (outOfBounds(i))
    {
        throw new IndexOutOfBoundsException("Index not in heap : " + i);
    }

    int current = i;
    Customer temp = this.heap[i];

    while (current > 0) 
    {           
        if (this.comparator.compare(this.heap[current],
                    this.heap[parent(current)]) >= 0)
        {
            break;
        }

        this.heap[current] = this.heap[parent(current)];
        current = parent(current);

    }

    this.heap[current] = temp;

}

编辑:

比较方法定义如下:

        @Override
        public int compare(Customer cust1, Customer cust2) {

            return cust1.priority() - cust2.priority();

        }

1 个答案:

答案 0 :(得分:0)

我最后写了一个方法,它在堆中的每个元素上执行上面的方法,并且有效。它不是一个优雅的解决方案,但它完成了工作。