Inserted 10 into the min-heap: 10
Inserted 3 into the min-heap: 3 10
Inserted 2 into the min-heap: 2 10 3
Inserted 4 into the min-heap: 2 4 3 10
Inserted 5 into the min-heap: 2 4 3 10 5
Inserted ...
Deletion - O(log n) Time and O(n) Space
Removing the smallest element (the root) from a Min-Heap involves the following steps:
Replace the root (or the element to be deleted) with the last element in the heap.
Remove the last element from the heap, since it has been moved to the root.
Heapify-down: The element now at the root may violate the Min-Heap property, so perform heapify starting from the root to restore the heap property.
The heapify operation is used to place an element in its correct position within the heap so that the heap property is maintained. A heapify operation can also be used to create a min heap from an unsorted array. This is done by starting at the last non-leaf node and repeatedly performing the "heapify down" operation until all nodes satisfy the heap property.
Heap Sort: Min-heap is used to implement heap sort, an efficient O(n log n) sorting algorithm.
Priority Queue: Min-heap ensures the smallest element is always at the root, enabling efficient priority queue operations.
Dijkstra’s Algorithm: Min-heap stores vertices by minimum distance for efficient shortest-path computation.
Huffman Coding: Min-heap implements a priority queue to build optimal prefix codes.
Merge K Sorted Arrays: Min-heap efficiently merges K sorted arrays into one sorted array.
Advantages of Min-heap Data Structure
Fast Insertion and Deletion: Supports insertion and removal in O(log n) time, maintaining heap property efficiently.
Quick Access to Minimum: The smallest element is always at the root, retrievable in O(1) time.
Compact Storage: Can be implemented using arrays, saving memory compared to pointer-based structures.
Heap-based Sorting: Enables efficient sorting algorithms like heap sort with O(n log n) complexity.
Wide Applicability: Used in CPU/job scheduling (priority scheduling), graph algorithms like Dijkstra’s shortest path and Prim’s MST, and data compression like Huffman coding.