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