5.2 Binary Heap An Min Heap
5.2 Binary Heap An Min Heap
A Binary Heap is a complete Binary Tree which is used to store data efficiently to get the max or min
element based on its structure.
A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at the root must be minimum
among all keys present in Binary Heap..
The new element is initially appended to the end of the heap (as the last element of the array). The heap
property is repaired by comparing the added element with its parent and moving the added element up a level
(swapping positions with the parent). This process is called "percolation up". The comparison is repeated until
the parent is larger than or equal to the percolating element.
2. Deletion in Min-Heap Data Structure:
Removing the smallest element (the root) from the min heap. The root is replaced by the last element in the
heap, and then the heap property is restored by swapping the new root with its smallest child until the parent
is smaller than both children or until the new root reaches a leaf node.
Replace the root or element to be deleted with the last element.
Delete the last element from the Heap.
Since the last element is now placed at the position of the root node. So, it may not follow the heap
property. Therefore, heapify the last node placed at the position of the root.
Suppose the Heap is a Min-Heap as:
Min-Heap Data Structure
Min-Heap Data Structure
Efficient insertion and deletion: Min heap allows fast insertion and deletion of elements with a time
complexity of O(log n), where n is the number of elements in the heap.
Efficient retrieval of minimum element: The minimum element in a min heap is always at the root of
the heap, which can be retrieved in O(1) time.
Space efficient: Min heap is a compact data structure that can be implemented using an array or a binary
tree, which makes it space efficient.
Sorting: Min heap can be used to implement an efficient sorting algorithm such as heap sort with a time
complexity of O(n log n).
Priority Queue: Min heap can be used to implement a priority queue, where the element with the
minimum priority can be retrieved efficiently in O(1) time.
Versatility: Min heap has several applications in computer science, including graph algorithms, data
compression, and database systems.