Heap

#programming #data-structures

A heap is a complete binary tree with an additional ordering property.

A complete binary tree is one where every level is fully filled, except possibly the last
The last level is filled left to right.
This property allows easy storage in arrays.

Types

  1. Min heap : Every node it's children. Root is minimum
  2. Max heap : Every node it's children. Root is maximum

Array representation

For every node, at index i,


Core operations

Insert (push)

Steps :

Time complexity : O(logn), since height of tree is logn

Extract (pop)

Steps:

Time complexity : O(logn)


Heapify

This refers to the process of building a heap from an unsorted array

Naive approach

Insert element one by one, while continually maintaining heap property and fixing if violated.
Time complexity : O(nlogn)

Bottom up heapify

We assume that the last few elements are already leaf nodes. Since they have no children, they can violate no properties (note that property is only with children, not parent).

Precisely, the leaf nodes in an array of size n : n/2 to n1.
This means that the last non-leaf node is at index n/21

Therefore we iterate backwards from that index and go to zero.

At each node, since we would've already processed it's children, we need only to process the current node, and fix it's property (if broken) by using heapify-down.

The advantage is that, since at each node we only work on the existing subtree, and not the entire tree, heapify-down operation is less expensive than O(logn)

For n/2 nodes : Height = 0 O(1) work.
For n/4 nodes : Height = 1 O(1) work.
For n/8 nodes : Height = 2 O(2) work.

Therefore, total work is n×(1/2+1/4+1/8)=O(n)

Therefore,
Time complexity : O(n)

Note

When doing a heapify-down in a min heap, we must keep in mind to swap with the smaller child, if both children violate property of BST.
This guarantees the correctness of both subtrees being valid heaps, and reduces unnecessary overhead.

Keep in mind

Applications

Powered by Forestry.md