MinHeap
A min heap implementation where the smallest element is always at the root. Inherits fromHeap and overrides the heapify operations to maintain min heap property.
Constructor
Class Methods
from_list(mylist)
Create a min heap from a list of elements.The list of elements to be inserted into the heap.
An instance of the min heap with all elements from the list inserted.
Methods
MinHeap inherits all methods fromHeap, including:
raw_view()- Get internal array representationroot()- Get the root (minimum) valuepeek()- Get the minimum valuelast()- Get the last elementleft_index(index)- Get left child indexright_index(index)- Get right child indexparent_index(index)- Get parent indexhas_left(index)- Check if node has left childhas_right(index)- Check if node has right childhas_parent(index)- Check if node has parentinsert(value)- Insert a valueenumerate()- Get enumeration of heapcount()- Get number of itemsis_empty()- Check if heap is emptyprint()- Print heap contentsto_sorted_list()- Get sorted list (ascending for min heap)
heapify_up(index)
Perform heapify up operation for a min heap, moving smaller elements up the tree.The starting index.
heapify_down(index)
Perform heapify down operation for a min heap, moving larger elements down the tree.The starting index.
extract_min()
Return the minimum value from the heap and remove it.The minimum value from the heap.
Exception: If the heap is empty
Usage Examples
Basic Operations
Creating from List
Finding K Smallest Elements
Comparison: MinHeap vs Heap
Key Differences
Key Differences
| Feature | MinHeap | Heap (MaxHeap) |
|---|---|---|
| Root element | Minimum value | Maximum value |
| peek() returns | Smallest element | Largest element |
| Extract method | extract_min() | extract_max() |
| Heapify direction | Smaller values up | Larger values up |
| to_sorted_list() | Ascending order | Descending order |
| Use case | Finding minimums, priority queue with low priority first | Finding maximums, priority queue with high priority first |
Special Methods
MinHeap inherits all special methods fromHeap:
__repr__()- String representation in priority order__len__()- Number of items via len()__eq__(other)- Equality comparison