We started learning Heap property in class. Here is an exercise on the topic:
isHeap
Write the definition of a function named isHeap that receives three arguments as follows:
x : an array of ints
i : a valid index into the array x
n : the number of elements in the array xThe function returns true if the HEAP property holds among the array elements x[i]...x[n-1] , and false otherwise. The HEAP property is simply that for every value of j between i and n-1 , x[j] is not less than its heap children if they exist. (The heap children of x[j] are x[2j+1] and x[2j+2] .
My code:
bool isHeap (int x[], int n, int i) {
bool heap=true;
for (int j=i; j<n; j++) {
if ((2*j+1)<=(n-1)) {
if (x[j]>=x[2*j+1]&&x[j]>=x[2*j+2])
heap=true;
else
heap=false;
}
else
heap=true;
return heap;
}
}
CodeLab returns logical error:
Remarks:
⇒ fails for:
⇒ starting point: 0
⇒ 5 elements: 50 50 50 50 50⇒ Your code had an error during execution
I have a feeling it's something about correctness of boolean logic but can't see it right now..
Any suggestions?
Thanks!