gpt4 book ai didi

java - ArrayHeap 类不返回排序数组

转载 作者:太空宇宙 更新时间:2023-11-04 06:24:08 25 4
gpt4 key购买 nike

我正在使用java。

这是我的类(class)的代码:

/**
* 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;
}
}

我检查了我的代码,似乎无法找出导致此问题的原因。

谁能帮帮我吗?

最佳答案

你的算法有一个小错误:

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

关于java - ArrayHeap 类不返回排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27026733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com