zoukankan      html  css  js  c++  java
  • 基于最大堆的优先队列的实现

    二叉堆实现的链接https://www.cnblogs.com/wkhzwmr/p/15339229.html

    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.size -= 1
            self.down_adjust()
            return head # 返回出队的队头
    
        def up_adjust(self):
            '''
            插入上浮是插入到最后一个位置,然后与父节点进行元素交换
            '''
            child_index = self.size - 1
            parent_index = (child_index - 1) // 2
            # temp保存插入的叶子节点值,用于最后的赋值
            temp = self.array[child_index] # 保存插入节点的值
            while child_index > 0 and temp > self.array[parent_index]: # 循环条件是插入节点的索引大于0并且插入节点的值大于父节点
                # 无需真正交换,单向赋值即可
                self.array[child_index] = self.array[parent_index] #父节点的值赋值给该插入孩子节点的索引
                child_index = parent_index #父节点的索引赋值给孩子节点
                parent_index = (parent_index - 1) // 2 #对啊,这里为啥不用child_index啊 
            self.array[child_index] = temp
    
        def down_adjust(self):
            '''
            下沉操作时,从堆顶开始下沉,与孩子节点进行替换
            '''
            parent_index = 0
            # temp保存父节点值,用于最后的赋值
            temp = self.array[parent_index]
            child_index = 1
            while child_index < self.size:
                # 如果有右孩子,且右孩子大于左孩子的值,则定位到右孩子
                if child_index + 1 < self.size and self.array[child_index + 1] > self.array[child_index]:
                    child_index += 1
                # 如果父节点大于任何一个孩子的值,直接跳出
                if temp >= self.array[child_index]:
                    break
                # 无需真正交换,单向赋值即可
                self.array[parent_index] = self.array[child_index]
                parent_index = child_index
                child_index = 2 * child_index + 1
            self.array[parent_index] = temp
    
    
    queue = PriorityQueue()
    queue.enqueue(3)
    queue.enqueue(5)
    queue.enqueue(10)
    queue.enqueue(2)
    queue.enqueue(7)
    print(queue.dequeue())
    print(queue.dequeue())
    
    
    
    努力拼搏吧,不要害怕,不要去规划,不要迷茫。但你一定要在路上一直的走下去,尽管可能停滞不前,但也要走。
  • 相关阅读:
    JOIN中的外连接(external join)
    将流数据输出到Mysql中
    updataStateByKey算子的使用
    RDD算子的使用
    sparkstreaming 黑名单过滤
    sparkSQL中的example学习(3)
    sparkSQL中的example学习(1)
    sparkSQL中的example学习(2)
    shuffle调优
    回形取数
  • 原文地址:https://www.cnblogs.com/wkhzwmr/p/15339778.html
Copyright © 2011-2022 走看看