大顶堆的python实现

该博客介绍了如何使用Python实现大顶堆数据结构,包括插入、删除最大值及堆排序等操作。通过堆的性质,实现了高效地插入元素并保持堆的特性,以及删除最大值后重新调整堆。此外,还提供了建立堆和对数组进行排序的方法。
摘要由CSDN通过智能技术生成

堆的python实现

class Heap(object):
    """大顶堆的定义,实现插入和删除"""

    def __init__(self, capacity):
        self.a = [None] * (capacity + 1)
        self.n = capacity
        self.count = 0

    def insert(self, data):
        """插入一个数据"""
        if self.count >= self.n:
            return False
        self.count += 1
        i = self.count
        self.a[i] = data
        # 让新插入的节点与父节点对比大小。如果不满足子节点小于等于父节点的大小关系,
        # 我们就互换两个节点。一直重复这个过程,直到所有的子节点小于等于父节点。
        while int(i / 2) > 0 and self.a[i] > self.a[int(i / 2)]:
            temp = self.a[i]
            self.a[i] = self.a[int(i / 2)]
            self.a[int(i / 2)] = temp
            i = int(i / 2)
        print(self.a)
        return True

    def remove_max(self):
        """删除大顶堆最大值"""
        if self.count == 0:
            return False
        self.a[1] = self.a[self.count]
        self.count -= 1
        self.heapify()
        print(self.a)
        return True

    def heapify(self):
        # 删除堆顶元素之后,就需要把第二大的元素放到堆顶,那第二大元素肯定会出现在左右子节点中。
        # 然后我们再迭代地删除第二大节点,以此类推,直到叶子节点被删除。
        i = 1
        while True:
            max_pos = i
            if 2 * i <= self.count and self.a[i] < self.a[2 * i]:
                max_pos = 2 * i
            if 2 * i + 1 <= self.count and self.a[max_pos] < self.a[2 * i + 1]:
                max_pos = 2 * i + 1
            if max_pos == i:
                self.a[self.count + 1] = None
                break
            temp = self.a[i]
            self.a[i] = self.a[max_pos]
            self.a[max_pos] = temp
            i = max_pos

    def build_heap(self, arr):
        """算法从第1个下标开始计算,所以需要插入站位None"""
        n = len(arr)
        arr.insert(0, None)
        # 我们只对 n/2 开始到 1的数据进行堆化,下标是n/2+ 1 到 n 的节点都是叶子节点,不需要堆化,
        # 对于完全二叉树来说,下标是n/2+ 1 到 n 的节点都是叶子节点
        for i in range(int(n / 2), 0, -1):
            self.heapify_by_arr(arr, n, i)
        return arr

    @staticmethod
    def heapify_by_arr(arr, l, i):
        while True:
            max_pos = i
            if 2 * i <= l and arr[i] < arr[2 * i]:
                max_pos = 2 * i
            if 2 * i + 1 <= l and arr[max_pos] < arr[2 * i + 1]:
                max_pos = 2 * i + 1
            if max_pos == i:
                break
            temp = arr[i]
            arr[i] = arr[max_pos]
            arr[max_pos] = temp
            i = max_pos

    def sort_by_heap(self, arr):
        """利用堆进行数组排序"""
        k = len(arr)
        arr = self.build_heap(arr)
        while k > 1:
            temp = arr[k]
            arr[k] = arr[1]
            arr[1] = temp
            k -= 1
            self.heapify_by_arr(arr, k, 1)
        print(arr)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值