For a project, am i working with heaps. In this project i have to "investigate" whether an array is a max heap.
These 2 rules apply for a max heap:
- The parent shall be bigger or equal to its child / children
- Each node, in a heap, shall contain an element
Therefore have i created 2 for loops checking whether these rules apply. Unfortunately for me, my code doesn't work.
I have 2 for loops:
//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};
The last for loop works, but for some reason i get a mistake in the first for loop. The loop can find a number. 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)
THE WHOLE CODE:
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;
}
}