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

标签 java priority-queue min-heap

我正在尝试使用最小堆实现优先级队列,但我的对象以错误的顺序从队列中出来。我的直觉告诉我问题出在我在队列中向上或向下筛选的方法,但我看不出问题出在哪里。有人可以看看我的算法,看看是否有任何明显的错误?预先感谢您。

这里是筛选的方法:

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();

        }

最佳答案

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

关于java - 使用最小堆实现优先级队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26691609/

相关文章:

java - 为什么 @jdbc 查询因连接超时而失败?

c++ - 恒定大小优先级队列 - 先插入还是先删除?

c++ - Dijkstra 算法 - 如何使用优先级队列或最小堆?

C:尝试实现 minHeapSort 然后打印它 - 无法使 for 条件正常工作

java - 我可以在 JDBC 准备好的查询中使用多个语句吗?

java - 具有多个 View 类型的 Recyclerview 相互通信?

java - 使用数组 : Insert and Remove Min (with duplicates) 实现最小堆

python - 从 heapq python 弹出最大值,Python 中有最大堆吗?

java - 空指针异常 - GPA HH 的 Java 程序

scala - 在我的算法中替换命令式 PriorityQueue