java - 它是堆最大值吗?
问题描述
对于一个项目,我是否正在使用堆。在这个项目中,我必须“调查”一个数组是否是一个最大堆。
这 2 条规则适用于最大堆:
- 父母应大于或等于其孩子/孩子
- 堆中的每个节点都应包含一个元素
因此,我创建了 2 个用于检查这些规则是否适用的循环。对我来说不幸的是,我的代码不起作用。
我有 2 个 for 循环:
//Checks if there's a 0 value in the array. If so: Return false
for (int i = 1; i <= A.length; i++) {
System.out.println("A.length: " + A[i]);
if (A[i] == 0) {
System.out.println("weweh: "+ A[i]);
return false;
}
//Checks if either left or right child have a bigger value than itself
for (int i = 1; i <= (A.length - 2) / 2; i++) {
System.out.println("A: " + i);
if (A[i] < A[2 * i] || A[i] < A[2 * i + 1]) {
return false;
}
}
//the array
int A[] = {0, 40, 35, 30, 25, 15, 10, 5};
最后一个 for 循环有效,但由于某种原因,我在第一个 for 循环中出错。循环可以找到一个数字。Lets say that i picked 15 to be equal with A[i], then it would work and return false, but when the selected number 0 isn't there, then it sends me the error, and it wont go further for the second loop .
//Error:
A.length: 40
A.length: 35
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
A.length: 30
A.length: 25
A.length: 15
A.length: 10
A.length: 5
at ismaxheap.IsMaxHeap.MaxHeap(IsMaxHeap.java:24)
at ismaxheap.IsMaxHeap.main(IsMaxHeap.java:15)
/Users/yusuf/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
整个代码:
public class IsMaxHeap {
public static void main(String[] args) {
MaxHeap();
System.out.println("Max Heap: " + MaxHeap());
}
public static boolean MaxHeap() {
int A[] = {0, 40, 35, 30, 25, 15, 10, 5};
for (int i = 1; i <= A.length; i++) {
System.out.println("A.length: " + A[i]);
if (A[i] == 0) {
System.out.println("weweh: "+ A[i]);
return false;
}
}
for (int i = 1; i <= (A.length - 2) / 2; i++) {
System.out.println("A: " + i);
if (A[i] < A[2 * i] || A[i] < A[2 * i + 1]) {
return false;
}
}
return true;
}
}
解决方案
在您的第一个循环中,您使用<=
for (int i = 1; i <= A.length; i++)
既然您正在尝试访问A[i]
,i == A.length
那么您就超出了范围。
应该:
for (int i = 1; i < A.length; i++)
现在我不知道为什么你从索引 1 开始,因为 Java 中的索引从 0 开始。
处理一个孩子的特殊情况
当数组长度为 3 时就是这种情况(因为忽略了零索引)
所有你需要检查的是是否A[2] < A[1]
是一个最大堆,否则立即返回 false。
否则执行正常循环。
推荐阅读
- teamcity - 为什么在 VCS Root 中的分支规范更改后未触发功能分支构建?
- if-statement - Case 语句中的 IF 语句在 VHDL 中没有按预期工作
- mysql - Olingo/JPA 不在批处理请求中存储外键
- java - 为什么 PlanningVariable 的值在求解后不会改变?# OptaPlanner
- qt - 从 RPi4 迁移到 NVIDIA Jetson Nano 时出现 Qt-default 版本问题
- node.js - NodeJS 应用程序因“错误 R10(启动超时)-> Web 进程未能在启动后 60 秒内绑定到 $PORT”而失败
- flutter - 如何在颤动中垂直居中容器子项
- webpack - 如何在 ExtJS APP 中包含本地 JS 和 CSS 文件?
- docker - 不支持将 Docker Compose 迁移到 Kubernetes Volume Mount
- zfs - 多个磁盘上的 ZFS 数据同时损坏