0

I know that for a heap to be max ordered heap, the keys of parent nodes should be greater than or equal to those of the children and the highest key should be in the root node. I just wanted to make sure if the way I am thinking of it is right -

If I want to check if a given array of comparable object is a max ordered heap

boolean isItMaxOrdered(Comparable[] a) {
    //Check for 2 * i where i is the index of the first element
    //Check for 2 * i + 1 element where i is the index of the first element
    //Compare if element i is greater than 2 * i and also if (2 * i) is greater than (2 * i + 1)th element
    boolean check = false;
    for(int i = 0; i < a.length; i++) {
        if((2 * i + 1) < a.length)
            if(a[i].compareTo(a[2 * i]) > 0 && a[i].compareTo(a[2 * i + 1]) > 0 && a[2 * i].compareTo(a[2 * i + 1]) > 0)
                check = true;
            else
                check = false;
    }
    return check;
}
NatureDevil
  • 483
  • 1
  • 4
  • 14
  • But shouldn't that be a condition that should be true for all the values contained in the list? The only way I can account for that is setting check to true for all values that satisfy or false otherwise. – NatureDevil Mar 20 '15 at 04:22
  • Actually, I was mistaken. You should `return true;` at the very end. In the loop, check for whether the condition is false, since you can `return false` immediately. No need to continue checking, since one mis-ordering means the entire heap isn't max ordered. – royhowie Mar 20 '15 at 04:25

0 Answers0