# Binary Heap in C++

## Introduction:

Binary heap is a fundamental data structure commonly used in computer science for efficient implementation of priority queues. It is a complete binary tree where each node has a value smaller than or equal to its children if it's a min-heap or greater if it's a max-heap.

## Binary Heap:

A binary heap is typically represented as an array, where the parent-child relationships are defined based on the indices of the array elements. In a binary heap, for any node at index i:

• Its left child is at index 2*i + 1.
• Its right child is at index 2*i + 2.
• Its parent is at index (i - 1) / 2.

There are two types of binary heaps: min-heap and max-heap.

• In a min-heap, the value of each node is less than or equal to the values of its children.
• In a max-heap, the value of each node is greater than or equal to the values of its children.

The key property of a binary heap is the heap order property, which ensures that the root node (at index 0) contains the minimum (or maximum) element in a min-heap (or max-heap, respectively).

## Construction:

A binary heap is typically represented as an array, where the children of the node at index i are located at indices 2i+1 and 2i+2. This representation allows for efficient storage and manipulation of the heap structure. Consider the following example:

In array form, the same heap would be represented as: [5, 9, 11, 14, 18, 19, 21].

## Operations on Binary Heap:

• Insertion: When a new element is added to the heap, it is placed at the bottom, maintaining the complete binary tree property. Then, it is "bubbled up" or "percolated up" to its correct position by comparing it with its parent and swapping if necessary.
• Deletion: Removal of the root element from the heap. After removal, the last element in the array takes the root's place. Then, it is "bubbled down" or "percolated down" to its correct position by comparing it with its children and swapping if necessary.
• Heapify: This operation builds a heap from a given array. It starts from the last non-leaf node and performs the "bubble down" operation until all nodes satisfy the heap property.
• Extract Max/Min: This operation removes and returns the maximum (for max heap) or minimum (for min heap) element from the heap. It involves removing the root element and rearranging the heap to maintain its properties.

### Implementation:

Explanation:

• The program defines a class MinHeap to encapsulate the heap operations.
• In the MinHeap class, there is a private member heap which is a vector storing the elements of the heap.
• The heapify function is a helper function used to maintain the min-heap property. It takes an index i as input and recursively adjusts the subtree rooted at index i to ensure it satisfies the min-heap property.
• The insert function inserts a new element into the heap. It first adds the element to the end of the vector and then performs a "bubble-up" operation to move the element up the tree until its parent is smaller than or equal to it, ensuring the min-heap property is maintained.
• The extractMin function removes and returns the minimum element from the heap. It first checks if the heap is empty, returning -1 if so (this could alternatively throw an exception).
• It then replaces the root (minimum element) with the last element in the vector, removes the last element, and calls heapify on the root to restore the min-heap property.
• In the main function, an instance of MinHeap is created, and several elements are inserted into it using the insert function. Then, the minimum element is extracted from the heap using extractMin and printed to the console.

Program Output:

Time Complexity Analysis:

• Insertion (insert): Inserting an element into a binary heap involves adding it at the end of the heap array and then performing the heapifyUp operation, which has a time complexity of O(log n), where n is the number of elements in the heap. Therefore, the overall time complexity for insertion is O(log n).
• Extraction (extractMin): Extracting the minimum element from a min-heap requires removing the root node and replacing it with the last element of the heap array. This is followed by the heapifyDown operation, which has a time complexity of O(log n), where n is the number of elements in the heap. Hence, the overall time complexity for extraction is O(log n).
• Accessing Minimum Element: Accessing the minimum element in a min-heap is a constant-time operation, as the minimum element is always stored at the root node. Therefore, the time complexity for accessing the minimum element is O(1).

## Application of Binary Heaps:

Binary heaps find applications in various algorithms and data structures due to their efficient nature:

• Priority Queues: Binary heaps are commonly used to implement priority queues, where elements are inserted with an associated priority and retrieved in order of priority.
• Heap Sort: Heap sort is a comparison-based sorting algorithm that uses binary heaps to sort elements in ascending (or descending) order efficiently.
• Dijkstra's Algorithm: This algorithm for finding the shortest paths between nodes in a graph uses a priority queue, often implemented using a binary heap, to efficiently select the next node to explore.

## Advantages:

• Simple Representation: Binary Heaps can be efficiently represented using arrays, resulting in reduced overhead compared to tree-based representations.
• Efficient Operations: Insertion, deletion, and retrieval of the maximum or minimum element can be performed in logarithmic time complexity.

## Conclusion:

In conclusion, the binary heap data structure in C++ provides an efficient solution for maintaining a priority queue, allowing for quick access to the highest (or lowest) priority element. Through its balanced tree structure and heap properties, binary heaps offer logarithmic time complexity for both insertion and extraction of elements, making them suitable for a wide range of applications where fast access to prioritized data is essential.

By implementing heap operations such as insertion, deletion, and heapify functions, developers can harness the power of binary heaps to optimize algorithms and improve overall performance in various software projects. As a fundamental tool in computer science and programming, mastering the concepts and implementation of binary heaps in C++ opens doors to solving complex problems with elegance and efficiency.

For Videos Join Our Youtube Channel: Join Now