I implemented a recursive algorithm to check if an array is a min-heap. I can't figure out what the worst case time complexity should be. Here's the code:
CHECK-MIN-HEAP(A, i, n)
if i > (n - 1) / 2
return true
if A[i] > A[left(i)] or A[i] > A[right(i)]
return false
return CHECK-MIN-HEAP(A, left(i), n) and CHECK-MIN-HEAP(A, right(i), n)
A brief explanation: the base case is represented by the case in which a node is a leaf. This because the element A[(n-1)/2] represent the last not-leaf node. The other base case is when the min-heap condition is violated. In the recursive case we check if the left and right subtrees are heaps.
So in best case, when the array isn't an heap, we have a constant time complexity. In the worst one, when the array is an heap, the function check all the nodes of the heap and 'cause the height of the heap is logn, the time complexity should be O(logn). Is correct? Or the time complexity is O(n)?
A[right(i)]
may not always exist in the checkA[i] > A[right(i)]
. Consider the heap 1, 2, 3, 4. In this heap, 2 has a left-child (4) but no right-child. – Cem