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