Python实现最小堆(Min Heap)

最小堆的特点,最小值一定在第一个元素


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值