2

I understand that deletion in a Min/Max heap occurs always at the root, and when it happens, the deleted node is replaced by the last node in the Binary Heap, then the node is heapify downward to find its correct position, making this on average a O(logN) operation.

Now, Binary Heap is commonly represented over arrays. Here comes the question: if deletion in an array at position [0] is log(n), because all right cells must be shift to the left, to fill the empty cell. Then, **why does a Min/Max Heap Binary Tree (which is represented over an array) is consider to be a O(logN) operation ** and not a O(n) operation.

Thanks for throwing light on the confusion!

Anatolii
  • 14,139
  • 4
  • 35
  • 65
Jimmy
  • 377
  • 4
  • 5
  • 16

2 Answers2

4

...if deletion in an array at position [0] is log(n), because all right cells must be shift to the left, to fill the empty cell. Then, **why does a Min/Max Heap Binary Tree (which is represented over an array) is consider to be a O(logN) operation ** and not a O(n) operation.

In your first paragraph, you correctly pointed out that to remove a root element, it has to be replaced by the last element of the heap, and then a heapify operation is applied from the root downwards. Not all right cells should be shifted to the left in this case, because you update only a value at the root (you may also update the last element, or decrement the heap size to ignore the element for your heapify operations), and then you heapify from the root.

heapify is O(log(n)) regardless of whether a heap is implemented over an array or as a tree. Moreover, it's usually implemented over an array :)

Anatolii
  • 14,139
  • 4
  • 35
  • 65
0

A heap is a binary tree and heapifying goes from the root to some leaf. The height of a heap is approx. a logarithm of a number of nodes in the tree, so at most log(N) swaps are needed. All elements of the underlying array need not be shifted, just a few on the downward path through the tree.

CiaPan
  • 9,381
  • 2
  • 21
  • 35