A min-heap is a complete binary tree where all levels, except the last level, are completely filled. There is no “hole” in the tree. A min-heap should meet these criteria: the parent’s value is less than both children’s values. The smallest value is at the root.

This post is the min-heap implementation. The max-heap is in opposite order. Note the search and traversal in the min-heap is the same as the max-heap, so please refer to the max-heap for these two operations.

min heap implementation

Table of Content



Map of heap implementations

Part 1 – Max-heap implementation

you are here

Part 2 – Min-heap implementation


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 the 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 in the heap based on its value compared to its parent. If its value is less than its parent, it should be switched the position with its parent. We keep doing it until it is below a node with a smaller value and above one or two nodes with larger values. We call this process bubble up.

Java

Javascript

Python


Remove

The removal operation is to remove the element at the root, which has the smallest value. This is the first element in the underlying 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. We keep doing it until it is below a node with a smaller value and above one or two 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.

Java

Javascript

Python


Free download

Download Min-heap implementation in Java, JavaScript and Python
Data structures introduction

What is the time complexity of insertion and deletion in a heap?

Since the heap is a complete binary tree, the time complexity is O(logn).

What is a min-heap?

A min-heap is a complete binary tree where all levels, except the last level, are completely filled. There is no “hole” in the tree. A min-heap should meet these criteria: the parent’s value is less than both children’s values. The smallest value is at the root.