对于一个项目,我是否正在使用堆。在这个项目中,我必须“调查”一个数组是否是一个最大堆。
这 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;
}
}