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

Table of Content


What is behind min-heap?

Min heap is a complete tree conceptually. Since there is no hold, it can be represented as an array. Each node’s position in the tree is corresponding to the index in the array.

min heap

The relationship between nodes has the formulas:

parentPos = (pos-1)/2
left = 2*pos+1
right=2*pos+2

This post is min heap implementation. The max heap is opposite order. Note the search and traversal in min-heap implementation is the same as max-heap.


Map of heap implementations

Part 1 – Max-heap implementation

you are here

Part 2 – Min-heap implementation
Part 3 – Priority queue implementation with heap iterative solution
Part 4 – Priority queue implementation with heap recursive solution


Insert

We declare 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, we put the new value at the end of the array. Then we 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 smaller node and above a larger one. We call this process heap up (or trickle up).

Java

Javascript

Python


Remove

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

Java

Javascript

Python


Free download

Download Min-heap implementation in Java, JavaScript and Python
Download combined Data Structures implementations in Java
Download combined Data Structures implementations in JavaScript
Download combined Data Structures implementations in Python