Basics of Heaps

·

2 min read

Before getting into what is a heap, you gotta know where Heap is used. Heaps are used for Heap sort, sorting a list of numbers in O(n.logn). Interestingly Heaps are more frequent in implementing a Priority Queue rather than using for heap sort.

What is a Heap ?

A heap is a complete binary tree, each of whose elements contains a value that is either greater than / equal to (or) lesser than / equal to the value of each of it's children.

Let's break the definition of Heap

#1: Complete Binary Tree

A complete binary tree is a binary tree in which all the levels are completely filled except possibly the lowest one, which is filled from the left. Group 1.png

Since the heap is a complete / almost complete binary tree, the height of heap is log(n)

#2: Types of Heaps

Value of each element of a heap should be either greater than / equal to (or) lesser than / equal to its's descendants

So basically according to this there are two types of heaps :

  1. Max Heap : Node element should be greater than or equal to it's left child and right child and it is recursively true for all it's subtrees.
  2. Min Heap : Node element should be less than or equal to it's left child and right child and it is recursively true for all it's subtrees.

    The leaf node always follows the max/min heap property because it doesn't have any descendants.

Group 2.png