Java 用最小堆实现优先级队列
我试图使用minheap实现优先级队列,但是我的对象以错误的顺序从队列中出来。我的直觉告诉我,问题在于我在队列中上下筛选的方法,但我看不出问题在哪里。有没有人能看看我的算法,看看是否有什么错误是显而易见的?先谢谢你 以下是筛选的方法:Java 用最小堆实现优先级队列,java,priority-queue,min-heap,Java,Priority Queue,Min Heap,我试图使用minheap实现优先级队列,但是我的对象以错误的顺序从队列中出来。我的直觉告诉我,问题在于我在队列中上下筛选的方法,但我看不出问题在哪里。有没有人能看看我的算法,看看是否有什么错误是显而易见的?先谢谢你 以下是筛选的方法: private void walkDown(int i) { if (outOfBounds(i)) { throw new IndexOutOfBoundsException("Index not in heap : " + i
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;
}
编辑:
比较方法定义如下:
@Override
public int compare(Customer cust1, Customer cust2) {
return cust1.priority() - cust2.priority();
}
我最终编写了一个方法,在堆中的每个元素上执行上述方法,这是有效的。这不是一个优雅的解决方案,但它完成了任务。您可以发布您的比较方法吗?在这种情况下,它似乎被用来做很多逻辑工作。还有称为左和右的全局对象吗?同时使用名为right的布尔值可能不是一个好主意。
@Override
public int compare(Customer cust1, Customer cust2) {
return cust1.priority() - cust2.priority();
}