# Implement min heap

Min heap is a complete binary tree, in which all levels are completely filled and all the nodes in the last level are as left as possible. Min heap also meets this criteria: the parent’s key is less than both children’s keys. The smallest value is at the root. This post is about how to implement min heap.

max heap is opposite order. Note the search and traversal in min heap implementation is the same as max heap, so please refer to max heap for these two operation implementations.

### Concepts

A heap is a complete binary tree conceptually. The underlying data structure is an array. Each node’s position in the heap is corresponding to the index in the array. The root’s position is 0, corresponding to the index 0. The node’s position increases by 1 from left to right, from upper level to lower level.

The formula to get the parent and two children’s positions from the current node’s position in a heap:
parentPos = (pos-1)/2
left = 2*pos+1
right=2*pos+2

### Insert

In MinHeap class, there are three attributes: heap, length and maxSize. heap is an array. maxSize is the max length of the array. It is used to initialize the array. length is actual number of elements in the array. It starts from 0.

To insert a new element, you put the new value at the end of the array. Then you move it up based on its value compared to its parent. If it’s value less than its parent, it should be switched the position with its parent, until it is below a node with smaller value and above nodes with larger values. We call this process bubble up.

## Python

### Remove

The removal operation is to remove the element with the smallest value, which is the first one in the array. When you remove the first element in the array, you move the last element in the array to the first to fill out the empty spot. But this element’s value might be larger than its children’s. To correct this, you compare its value with its children’s values, and switch with the child with the smaller value, until it is below a node with smaller value and above nodes with larger values. This process is called bubble down. Bubble down is more complicated than bubble up because it has two children to compare.