博客
关于我
用最大堆实现最大优先队列(Python)
阅读量:382 次
发布时间:2019-03-05

本文共 2567 字,大约阅读时间需要 8 分钟。

优先队列的实现:基于最大堆的Python代码示例

优先队列是一种常见的数据结构,常用于需要根据一定优先级进行排序的操作。在本文中,我们将基于最大堆的实现方式来介绍优先队列的实现方法。

优先队列的结构

优先队列的存储结构通常采用数组形式。为了方便实现,数组的长度会根据需要进行动态扩容。每个元素的位置决定了其在队列中的优先级。当元素数量超过数组长度时,需要对数组进行扩容,以确保有足够的空间存储新元素。

优先队列的实现步骤

优先队列的实现主要包括以下几个步骤:

  • 初始化:创建一个空的数组用于存储队列元素,初始大小设为0。
  • 入队操作:将元素添加到数组的末尾,并调用up_adjust方法进行上调整,确保最大堆的性质。
  • 出队操作:删除队列头元素,并调用down_adjust方法进行下调整,以恢复最大堆的结构。
  • 上调整(up_adjust):从叶子节点开始,逐步向上移动,比较当前节点与其父节点的值,确保最大堆的性质。
  • 下调整(down_adjust):从根节点开始,逐步向下移动,找到最大的元素,将其移动到根节点位置。
  • 代码实现

    以下是优先队列的Python代码实现:

    class PriorityQueue:    def __init__(self):        self.array = []        self.size = 0    def enqueue(self, element):        self.array.append(element)        self.size += 1        self.up_adjust()    def dequeue(self):        if self.size <= 0:            raise Exception('队列为空')        head = self.array[0]        self.array[0] = self.array[self.size - 1]        self.array.pop(0)        self.size -= 1        self.down_adjust()        return head    def up_adjust(self):        child_index = self.size - 1        parent_index = (child_index - 1) // 2        temp = self.array[child_index]        while child_index > 0 and temp > self.array[parent_index]:            self.array[child_index] = self.array[parent_index]            child_index = parent_index            parent_index = (child_index - 1) // 2        self.array[child_index] = temp    def down_adjust(self):        parent_index = 0        temp = self.array[parent_index]        child_index = 1        while child_index < self.size and self.array[child_index] <= self.array[child_index + 1]:            temp = self.array[child_index]            child_index += 1        self.array[parent_index] = temp        parent_index = child_index        child_index = 2 * parent_index + 1    def printList(self):        print(self.array)# 创建优先队列实例queue = PriorityQueue()# 添加元素queue.enqueue(3)queue.enqueue(6)queue.enqueue(2)queue.enqueue(8)queue.enqueue(4)# 打印当前队列状态print("当前队列状态:")queue.printList()# 出队操作print("\n开始出队操作:")result = queue.dequeue()print(f"出队元素:{result}")queue.printList()# 再次出队print("\n再次出队操作:")result = queue.dequeue()print(f"出队元素:{result}")queue.printList()# 添加新元素queue.enqueue(1)queue.printList()# 最终出队print("\n最后出队操作:")result = queue.dequeue()print(f"出队元素:{result}")queue.printList()

    代码解释

  • 类定义:定义了一个名为PriorityQueue的类,用于实现优先队列。
  • 初始化方法__init__方法初始化数组和大小,初始为空。
  • 入队方法enqueue方法将元素添加到数组末尾,并调用up_adjust进行上调整。
  • 出队方法dequeue方法删除队列头元素,并调用down_adjust进行下调整。
  • 上调整方法up_adjust方法从叶子节点开始,逐步向上调整最大堆的性质。
  • 下调整方法down_adjust方法从根节点开始,逐步向下调整最大堆的性质。
  • 打印方法printList方法打印当前队列状态。
  • 通过上述代码实现,可以清晰地看到优先队列的存储结构和操作流程。在实际应用中,可以通过自定义类扩展优先队列的功能,满足不同的需求。

    转载地址:http://ubvg.baihongyu.com/

    你可能感兴趣的文章
    OpenFeign 入门与实战
    查看>>
    OpenFeign源码学习
    查看>>
    OpenFeign的使用方式成功解锁
    查看>>
    OpenFeign组件声明式服务调用
    查看>>
    openfeign远程调用不起作用解决_使用Spring Boot的spring.factories进行注入---SpringCloud Alibaba_若依微服务框架改造---工作笔记007
    查看>>
    openfire开发(四)消息拦截器
    查看>>
    openfire源码解读之将cache和session对象移入redis以提升性能
    查看>>
    Openfire身份认证绕过漏洞复现+利用(CVE-2023-32315)
    查看>>
    OpenForest 开源项目安装与使用指南
    查看>>
    OpenGL glBlendFunc() 设置颜色混合 透明度叠加计算
    查看>>
    OpenGL 中“立即模式”是什么意思?
    查看>>
    opengl 教程(15) 摄像机控制(2)
    查看>>
    opengl 深度详解,多重采样时,如何在OpenGL纹理中解析深度值?
    查看>>
    OpenGL 的内置矩阵种种
    查看>>
    OpenGL/OpenGL ES 入门:基础变换 - 初识向量/矩阵
    查看>>
    OpenGL中shader读取实现
    查看>>
    OpenGL中旋转平移缩放等变换的顺序对模型的影响
    查看>>
    Opengl中的gluProject函数认识
    查看>>
    OpenGl介绍
    查看>>
    OPENGL半透明图像产生黑色光环
    查看>>