allizwell.jobsdoor360.in

Heap Implementation

Data Structures and Algorithms > Module 12: Heaps > Heap Implementation

Heap Implementation

A Heap is a complete binary tree that follows a special ordering rule called the Heap Property. Although we visualize a Heap as a tree, it is usually implemented using an array or a C++ vector. This makes Heap operations efficient because we can calculate the parent and child positions directly using index formulas. In this lesson, we will learn how to implement a Min Heap and a Max Heap from scratch in C++, including insertion, deletion, accessing the root, and displaying Heap elements.

1. How Is a Heap Implemented?

A Heap is a complete binary tree. Because every level is filled from left to right, we do not need separate pointers to connect its nodes.

Instead, we can store all the elements in an array. The first element represents the root, and the remaining elements are stored level by level.

Example of a Heap

              10
             /  \
           20    30
          / \    /
        40  50  60

The array representation is:

Index: 0 1 2 3 4 5

Value: 10 20 30 40 50 60

Notice that the tree is stored level by level. This representation is useful for both Min Heap and Max Heap implementations.

Important: The array representation does not change the logical tree structure. We use array indices to identify the parent and children of each node.

2. Index Formulas Used in Heap Implementation

We use zero-based indexing, which means the first element is stored at index 0.

If the current node is at index i, the positions of its parent and children are calculated as follows:

Parent Index = (i - 1) / 2

Left Child Index = 2 * i + 1

Right Child Index = 2 * i + 2

Example

Consider the following array:

Index: 0 1 2 3 4 5 6

Value: 50 30 40 10 20 35 25

Suppose we want to find the children of the node at index 1.

  • Left child index = 2 × 1 + 1 = 3
  • Right child index = 2 × 1 + 2 = 4
  • Left child value = 10
  • Right child value = 20

The parent of the node at index 1 is:

Parent index = (1 - 1) / 2 = 0

Parent value = 50

3. Main Operations in Heap Implementation

A Heap implementation generally supports the following operations:

  • Insert: Adds a new element while maintaining the Heap Property.
  • Peek: Returns the root element without removing it.
  • Delete Root: Removes the minimum element from a Min Heap or the maximum element from a Max Heap.
  • Heapify Up: Moves an element upward when its parent-child relationship violates the Heap Property.
  • Heapify Down: Moves an element downward to restore the Heap Property.
  • Display: Prints the elements in their internal array order.

4. Implementing a Min Heap

In a Min Heap, the parent node must always be smaller than or equal to its children.

Therefore, the smallest element is always stored at index 0.

Min Heap Structure

              10
             /  \
           20    30
          / \    /
        40  50  60

Its array representation is:

10 20 30 40 50 60

Min Heap Insertion

When we insert a new element into a Min Heap, we first place it at the end of the array. Then we compare it with its parent.

If the new element is smaller than its parent, we swap them. We continue this process until the Min Heap Property is restored.

Insertion Algorithm

  1. Add the new element at the end of the vector.
  2. Set the current index to the last position.
  3. Calculate the parent index.
  4. Compare the current element with its parent.
  5. If the current element is smaller, swap them.
  6. Move to the parent's index and repeat.
  7. Stop when the root is reached or the parent is smaller than or equal to the current element.

Example: Insert 15

Initial Min Heap:

              10
             /  \
           20    30
          / \
        40  50

Initial Array: 10 20 30 40 50

Step 1: Insert 15 at the end.

10 20 30 40 50 15

Step 2: Compare 15 with its parent, 30.

Since 15 is smaller than 30, swap them.

              10
             /  \
           20    15
          / \    /
        40  50  30

Step 3: Compare 15 with its new parent, 10.

Since 10 is smaller than 15, no more swapping is required.

Final Array: 10 20 15 40 50 30

Min Heap Deletion

In a Min Heap, deletion usually removes the root, which contains the smallest element.

The deletion process is:

  1. Replace the root with the last element.
  2. Remove the last element from the vector.
  3. Compare the new root with its children.
  4. Swap it with the smaller child if necessary.
  5. Continue downward until the Min Heap Property is restored.

Example: Delete the Minimum Element

Initial Min Heap:

              10
             /  \
           20    30
          / \    /
        40  50  60

The last element is 60. Move it to the root and remove its previous position.

              60
             /  \
           20    30
          / \
        40  50

Compare 60 with its children, 20 and 30. Swap it with the smaller child, 20.

              20
             /  \
           60    30
          / \
        40  50

Now compare 60 with 40 and 50. Swap it with 40.

              20
             /  \
           40    30
          / \
        60  50

Deleted Element: 10

Final Array: 20 40 30 60 50

5. Complete C++ Implementation of Min Heap

The following program implements a Min Heap using a C++ vector. It supports insertion, deletion, accessing the minimum element, and displaying the Heap.

#include <iostream>
#include <vector>
using namespace std;

class MinHeap {

private:

    vector<int> heap;

    // Restore Min Heap Property upward
    void heapifyUp(int index) {

        while (index > 0) {

            int parent = (index - 1) / 2;

            if (heap[index] < heap[parent]) {

                swap(heap[index], heap[parent]);

                index = parent;

            } else {

                break;
            }
        }
    }

    // Restore Min Heap Property downward
    void heapifyDown(int index) {

        int n = heap.size();

        while (true) {

            int left = 2 * index + 1;
            int right = 2 * index + 2;

            int smallest = index;

            if (left < n &&
                heap[left] < heap[smallest]) {

                smallest = left;
            }

            if (right < n &&
                heap[right] < heap[smallest]) {

                smallest = right;
            }

            if (smallest != index) {

                swap(heap[index], heap[smallest]);

                index = smallest;

            } else {

                break;
            }
        }
    }

public:

    // Insert a new element
    void insert(int value) {

        heap.push_back(value);

        int index = heap.size() - 1;

        heapifyUp(index);
    }

    // Return minimum element
    int peek() {

        if (heap.empty()) {

            cout << "Heap is empty" << endl;
            return -1;
        }

        return heap[0];
    }

    // Delete minimum element
    void deleteMin() {

        if (heap.empty()) {

            cout << "Heap is empty" << endl;
            return;
        }

        heap[0] = heap.back();

        heap.pop_back();

        if (!heap.empty()) {
            heapifyDown(0);
        }
    }

    // Display Heap
    void display() {

        for (int value : heap) {

            cout << value << " ";
        }

        cout << endl;
    }

    // Check whether Heap is empty
    bool isEmpty() {

        return heap.empty();
    }
};

int main() {

    MinHeap h;

    h.insert(40);
    h.insert(10);
    h.insert(30);
    h.insert(50);
    h.insert(20);

    cout << "Min Heap: ";
    h.display();

    cout << "Minimum Element: "
         << h.peek() << endl;

    h.deleteMin();

    cout << "After Deletion: ";
    h.display();

    return 0;
}

Output

Min Heap: 10 20 30 50 40

Minimum Element: 10

After Deletion: 20 40 30 50

Explanation of the Code

  • vector<int> heap stores the Heap elements.
  • heapifyUp() restores the Min Heap Property after insertion.
  • heapifyDown() restores the Min Heap Property after deletion.
  • insert() adds an element to the Heap.
  • peek() returns the smallest element without deleting it.
  • deleteMin() removes the smallest element.
  • display() prints the internal array representation.

6. Implementing a Max Heap

A Max Heap follows the opposite ordering rule. Every parent must be greater than or equal to its children.

Therefore, the largest element is always stored at index 0.

Max Heap Structure

              70
             /  \
           60    50
          / \    /
        40  30  20

Array: 70 60 50 40 30 20

Max Heap Insertion

Insertion in a Max Heap is similar to insertion in a Min Heap. The difference is that we swap the current element with its parent when the current element is greater.

Example: Insert 65

Initial Max Heap:

              70
             /  \
           60    50
          / \
        40  30

Insert 65 at the end:

70 60 50 40 30 65

Compare 65 with its parent, 50. Since 65 is greater, swap them.

              70
             /  \
           60    65
          / \    /
        40  30  50

Compare 65 with its new parent, 70. Since 70 is greater, stop.

Final Max Heap: 70 60 65 40 30 50

Max Heap Deletion

Deletion in a Max Heap removes the root, which contains the largest element.

  1. Replace the root with the last element.
  2. Remove the last element.
  3. Compare the new root with its children.
  4. Swap it with the larger child if necessary.
  5. Continue until the Max Heap Property is restored.

Example: Delete the Maximum Element

Initial Max Heap:

              70
             /  \
           60    50
          / \    /
        40  30  20

Replace 70 with the last element, 20, and remove its previous position.

              20
             /  \
           60    50
          / \
        40  30

Compare 20 with 60 and 50. Swap it with the larger child, 60.

              60
             /  \
           20    50
          / \
        40  30

Compare 20 with 40 and 30. Swap it with 40.

              60
             /  \
           40    50
          / \
        20  30

Deleted Element: 70

Final Array: 60 40 50 20 30

7. Complete C++ Implementation of Max Heap

This implementation uses a vector and supports insertion, deletion, accessing the maximum element, and displaying the Heap.

#include <iostream>
#include <vector>
using namespace std;

class MaxHeap {

private:

    vector<int> heap;

    // Restore Max Heap Property upward
    void heapifyUp(int index) {

        while (index > 0) {

            int parent = (index - 1) / 2;

            if (heap[index] > heap[parent]) {

                swap(heap[index], heap[parent]);

                index = parent;

            } else {

                break;
            }
        }
    }

    // Restore Max Heap Property downward
    void heapifyDown(int index) {

        int n = heap.size();

        while (true) {

            int left = 2 * index + 1;
            int right = 2 * index + 2;

            int largest = index;

            if (left < n &&
                heap[left] > heap[largest]) {

                largest = left;
            }

            if (right < n &&
                heap[right] > heap[largest]) {

                largest = right;
            }

            if (largest != index) {

                swap(heap[index], heap[largest]);

                index = largest;

            } else {

                break;
            }
        }
    }

public:

    // Insert a new element
    void insert(int value) {

        heap.push_back(value);

        int index = heap.size() - 1;

        heapifyUp(index);
    }

    // Return maximum element
    int peek() {

        if (heap.empty()) {

            cout << "Heap is empty" << endl;
            return -1;
        }

        return heap[0];
    }

    // Delete maximum element
    void deleteMax() {

        if (heap.empty()) {

            cout << "Heap is empty" << endl;
            return;
        }

        heap[0] = heap.back();

        heap.pop_back();

        if (!heap.empty()) {
            heapifyDown(0);
        }
    }

    // Display Heap
    void display() {

        for (int value : heap) {

            cout << value << " ";
        }

        cout << endl;
    }

    // Check whether Heap is empty
    bool isEmpty() {

        return heap.empty();
    }
};

int main() {

    MaxHeap h;

    h.insert(40);
    h.insert(10);
    h.insert(30);
    h.insert(50);
    h.insert(20);

    cout << "Max Heap: ";
    h.display();

    cout << "Maximum Element: "
         << h.peek() << endl;

    h.deleteMax();

    cout << "After Deletion: ";
    h.display();

    return 0;
}

Output

Max Heap: 50 40 30 10 20

Maximum Element: 50

After Deletion: 40 20 30 10

8. Understanding Heapify Up and Heapify Down

Heapify Up and Heapify Down are two important procedures used to maintain the Heap Property.

Heapify Up

Heapify Up is used after inserting a new element. The newly inserted element may violate the Heap Property with its parent.

  • Start from the newly inserted element.
  • Compare it with its parent.
  • Swap if the ordering rule is violated.
  • Continue toward the root.

Heapify Down

Heapify Down is commonly used after deleting the root element. The replacement element may violate the Heap Property with its children.

  • Start from the root or the affected position.
  • Compare the current element with its children.
  • Choose the appropriate child: smaller for Min Heap or larger for Max Heap.
  • Swap if the ordering rule is violated.
  • Continue toward the leaves.
Feature Heapify Up Heapify Down
Direction Child toward parent Parent toward child
Common Use After insertion After root deletion
Comparison Current element with parent Current element with children
Time Complexity O(log N) O(log N)

9. Heap Implementation Using C++ priority_queue

C++ also provides a built-in container adapter called priority_queue. It internally uses Heap functionality.

Max Heap Using priority_queue

#include <iostream>
#include <queue>
using namespace std;

int main() {

    priority_queue<int> pq;

    pq.push(40);
    pq.push(10);
    pq.push(30);
    pq.push(50);
    pq.push(20);

    cout << "Maximum: " << pq.top() << endl;

    cout << "Elements: ";

    while (!pq.empty()) {

        cout << pq.top() << " ";

        pq.pop();
    }

    return 0;
}

Maximum: 50

Elements: 50 40 30 20 10

Min Heap Using priority_queue

#include <iostream>
#include <queue>
#include <vector>
#include <functional>
using namespace std;

int main() {

    priority_queue<int, vector<int>, greater<int>> pq;

    pq.push(40);
    pq.push(10);
    pq.push(30);
    pq.push(50);
    pq.push(20);

    cout << "Minimum: " << pq.top() << endl;

    cout << "Elements: ";

    while (!pq.empty()) {

        cout << pq.top() << " ";

        pq.pop();
    }

    return 0;
}

Minimum: 10

Elements: 10 20 30 40 50

Remember: priority_queue<int> creates a Max Heap by default. To create a Min Heap, use greater<int> as the comparator.

10. Time Complexity of Heap Operations

A Heap containing N elements has a height of O(log N). Therefore, operations that move an element along the height of the tree take logarithmic time.

Operation Time Complexity Reason
Peek O(1) Root is directly available.
Insertion O(log N) Element may move upward through the Heap.
Delete Root O(log N) Replacement element may move downward.
Heapify Up O(log N) At most the height of the Heap is traversed.
Heapify Down O(log N) At most the height of the Heap is traversed.
Search O(N) Arbitrary elements are not fully sorted.
Display O(N) Every element is visited.

Space Complexity

The vector stores N elements, so the Heap requires O(N) space.

The iterative Heapify Up and Heapify Down methods use O(1) auxiliary space, excluding the storage used by the Heap itself.

11. Common Mistakes in Heap Implementation

  • Using the wrong parent or child index formula.
  • Forgetting that array indexing starts from 0.
  • Using the Min Heap comparison condition in a Max Heap.
  • Forgetting to remove the last element after moving it to the root.
  • Accessing the root when the Heap is empty.
  • Not checking whether child indices are within the vector size.
  • Swapping with the wrong child during Heapify Down.
  • Forgetting to restore the Heap Property after insertion or deletion.
  • Assuming that the internal array is completely sorted.

12. Important Interview Questions

Q1. Why are Heaps usually implemented using arrays?

A Heap is a complete binary tree, so its nodes can be stored level by level in an array. Parent and child positions can be calculated directly using index formulas, without storing pointers.

Q2. What is the parent index formula?

For a zero-based array, the parent index of a node at index i is (i - 1) / 2, using integer division.

Q3. What is the left child index formula?

The left child index is 2 × i + 1.

Q4. What is the right child index formula?

The right child index is 2 × i + 2.

Q5. What is the difference between Heapify Up and Heapify Down?

Heapify Up moves an element toward the root, while Heapify Down moves an element toward the leaves.

Q6. Why is insertion O(log N)?

A newly inserted element may move from the last level to the root. The height of a complete binary tree is O(log N).

Q7. Why is deletion of the root O(log N)?

After replacing the root with the last element, Heapify Down may move that element through the height of the Heap.

Q8. What is the time complexity of peek?

O(1), because the root is stored at index 0.

Q9. Can we implement a Heap without using a vector?

Yes. We can use a fixed-size array or a dynamically allocated array. A vector is convenient because it can grow as new elements are inserted.

Q10. Does displaying a Heap produce sorted output?

No. Displaying the internal array prints the level-order representation. It does not necessarily print the elements in sorted order.

13. Practice Problems

  1. Implement a Min Heap using a vector in C++.
  2. Implement a Max Heap using a vector in C++.
  3. Insert five elements into a Min Heap and show every swap.
  4. Insert five elements into a Max Heap and show every swap.
  5. Delete the root from a Min Heap and show each Heapify Down step.
  6. Delete the root from a Max Heap and show each Heapify Down step.
  7. Implement a function that returns the root without deleting it.
  8. Write a function to check whether a vector represents a valid Min Heap.
  9. Write a function to check whether a vector represents a valid Max Heap.
  10. Implement a Heap using a fixed-size array instead of a vector.

14. Summary

A Heap is generally implemented using an array or vector. Its complete binary tree structure allows us to calculate parent and child positions using simple index formulas.

  • Parent index = (i - 1) / 2.
  • Left child index = 2 × i + 1.
  • Right child index = 2 × i + 2.
  • Insertion adds an element at the end and uses Heapify Up.
  • Root deletion replaces the root with the last element and uses Heapify Down.
  • Peek takes O(1) time.
  • Insertion and root deletion take O(log N) time.
  • Displaying all elements takes O(N) time.
  • A vector makes dynamic Heap storage convenient in C++.
Key Takeaway: A Heap can be implemented efficiently using an array or vector. The most important parts of the implementation are the index formulas, Heapify Up, and Heapify Down. These operations help maintain the Heap Property after insertion and deletion.
Scroll to Top