Implement a heap data structure in C++.

Prerequisite:

Introduction to Priority Queues using Binary Heaps

 
We have introduced the heap data structure in the above post and discussed heapify-up, push, heapify-down, and pop operations. In this post, the implementation of the max-heap and min-heap data structure is provided. Their implementation is somewhat similar to std::priority_queue.

Max Heap implementation in C++:

Download  Run Code

Output:
 
Size is 3
15 3
Size is 4
45 5 4 2
true
Vector::at() : index is out of range(Heap underflow)
Vector::at() : index is out of range(Heap underflow)

Min Heap implementation in C++:

Following is the implementation min-heap data structure in C++, which is very similar to the max-heap implementation discussed above. The highlighted portion marks its differences with the max-heap implementation.

Download  Run Code

Output:
 
Size is 3
2 3
Size is 4
4 5 15 45
true
Vector::at() : index is out of range(Heap underflow)
Vector::at() : index is out of range(Heap underflow)

Following is the time complexity of implemented heap operations:

  1. push() and pop() takes O(log(n)) time.
  2. peek() and size() and isEmpty() takes O(1) time.

 
Exercise: Convert above code to use array instead of vector (check simple solution here).

 
Also See:

Min Heap and Max Heap Implementation in Java

 
References: https://en.wikipedia.org/wiki/Heap_(data_structure)