我正在使用java。
以下是我班级的代码:
/**
* Ensure that the ordering property of the heap holds after
* the insertion of an new element into the heap.
*/
private void interchangeUp() {
int current = size - 1;
int parent = (current - 1) / 2;
while(parent <= 0 && heapForm[current].compareTo(heapForm[parent]) < 0) {
swap(parent, current);
current = parent;
parent = (current - 1) / 2;
}
}
我查看了我的代码,似乎无法弄清楚导致此问题的原因。
任何人都可以帮助我吗?
答案 0 :(得分:1)
你在算法中有一个小错误:
private void interchangeUp() {
int current = size - 1;
int parent = (current - 1) / 2;
//while (parent <= 0 && heapForm[current].compareTo(heapForm[parent]) < 0) {
while (parent >= 0 && heapForm[current].compareTo(heapForm[parent]) < 0) {
swap(parent, current);
current = parent;
parent = (current - 1) / 2;
}
}