如何解决MinHeapify打印错误值
我试图弄清楚为什么minHeapify
不能正确排序。这是我的代码:
import java.util.List;
import java.util.ArrayList;
public class Heap {
public void insert2(List<Integer> heap,int value) {
if(heap.isEmpty()) {
heap.add(value);
}
else {
heap.add(value);
for(int index = heap.size() / 2 - 1;index >= 0;index--) {
minHeapify(heap,index);
}
}
}
public void minHeapify(List<Integer> heap,int index) {
int smallest = index;
int leftChildIndex = 2 * index + 1;
int rightChildIndex = 2 * index + 2;
if(leftChildIndex < heap.size() && heap.get(leftChildIndex) < heap.get(smallest)) {
smallest = leftChildIndex;
}
if(rightChildIndex < heap.size() && heap.get(rightChildIndex) < heap.get(smallest)) {
smallest = rightChildIndex;
}
if(smallest != index) {
int temp = heap.get(smallest);
heap.set(smallest,heap.get(index));
heap.set(index,temp);
minHeapify(heap,smallest);
}
}
public static void main(String[] args) {
List<Integer> input2 = new ArrayList<Integer>();
Heap heap2 = new Heap();
heap2.insert2(input2,3);
heap2.insert2(input2,4);
heap2.insert2(input2,48);
heap2.insert2(input2,9);
heap2.insert2(input2,5);
heap2.insert2(input2,2);
System.out.println(input2);
}
}
输出为[2,4,3,9,5,48]
最小堆的输出应始终进行排序。我对这个假设是否正确,应该是[2,48]
吗?
解决方法
您的实现是正确的,并且在您执行以下插入步骤之后的结果确实是[2,4,3,9,5,48]
。
最小堆的输出应始终进行排序
但是您对MinHeap
的想法有点误解,即每个节点都小于左右两个子节点。但是,正确的子节点可以更大,也可以小于其兄弟节点,只要大于其父节点即可。
因此,堆中表示的List
不能以正确的顺序排序。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。