【问题标题】:Implementing a priority queue with a min heap使用最小堆实现优先级队列
【发布时间】:2014-11-01 18:25:33
【问题描述】:

我正在尝试使用 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();

        }

【问题讨论】:

  • 你能发布你的比较方法吗?在这种情况下,它似乎用于执行大部分逻辑。
  • 还有全局对象叫左右吗?也有一个名为 right 的布尔值可能不是一个好主意。

标签: java priority-queue min-heap


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-06-09
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2018-08-10
    相关资源
    最近更新 更多