#check if array represents a min heap

1 messages · Page 1 of 1 (latest)

spiral steppe
#

`
public class Solution {

public static void main(String[] args) {
    int arr[] = {90, 15, 10, 7, 12, 2, 7, 12}; 
    int n = arr.length-1; 
   
    if (isHeap(arr,0, n)) { 
        System.out.println("Yes"); 
    } else { 
        System.out.println("No"); 
    } 

    

}
static boolean isHeap(int arr[], int i, int n) {
    
    // If (2 * i) + 1 >= n, then leaf node, so return true 
    if (i >= (n-1) / 2) { 
        
        return true; 
    } 

    // If an internal node and 
    // is greater than its 
    // children, and same is 
    // recursively true for the 
    // children 
    if (arr[i] >= arr[2 * i + 1] && arr[i] >= arr[2 * i + 2] && isHeap(arr, 2 * i + 1, n) && isHeap(arr, 2 * i + 2, n)) { 
        //System.out.print(i + " ");
        return true; 
    } 

    return false; 
     

}

}`

my base case (i >= (n-1) / 2) is not correct ,can someone help me figure out where am going wrong

brazen sequoiaBOT
#

<@&987246399047479336> please have a look, thanks.

#

Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#

boolean isMinHeap = checkMinHeap(arr, n);
System.out.println("Is the array a min heap? " + isMinHeap);
}

public static boolean checkMinHeap(int[] arr, int n) {
    for (int i = 0; i <= (n - 2) / 2; i++) {
        if (arr[i] > arr[2 * i + 1]) {
            return false;
        }
        if (2 * i + 2 < n && arr[i] > arr[2 * i + 2]) {
            return false;
        }
    }
    return true;
}

}