最小堆的特点,最小值一定在第一个元素
class MinHeap:
def __init__(self):
self.heap = []
def push(self, val):
self.heap.append(val)
self._sift_up(len(self.heap) - 1)
def pop(self):
if len(self.heap) == 0:
raise IndexError("pop from empty heap")
root = self.heap[0]
if len(self.heap) > 1:
self.heap[0] = self.heap.pop() # Move the last element to the root
self._sift_down(0) # Re-heapify the root element
return root
def _sift_up(self, index):
# If child node is less than parent node, then swap
while index > 0 and self.heap[index] < self.heap[(index - 1) // 2]:
parent_index = (index - 1) // 2
self.heap[index], self.heap[parent_index] = self.heap[parent_index], self.heap[index] # swap
index = parent_index
def _sift_down(self, index):
size = len(self.heap)
while True:
left_child_index = 2 * index + 1
right_child_index = 2 * index + 2
smallest = index
if left_child_index < size and self.heap[left_child_index] < self.heap[smallest]:
smallest = left_child_index
if right_child_index < size and self.heap[right_child_index] < self.heap[smallest]:
smallest = right_child_index
if smallest == index:
break
self.heap[index], self.heap[smallest] = self.heap[smallest], self.heap[index]
index = smallest
heap = MinHeap()
heap.push('E')
heap.push('C')
heap.push('A')
heap.push('B')
heap.push('F')
heap.push('D')
print(heap.pop()) # A
print(heap.pop()) # B
print(heap.pop()) # C
print(heap.pop()) # D
print(heap.pop()) # E
print(heap.pop()) # F