#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/3/18 19:47 # @Author : baoshan # @Site : # @File : heap.py # @Software: PyCharm Community Edition # 堆数据结构 class Heap(object): def __init__(self): self.data_list = [] def size(self): return len(self.data_list) def left_child(self, root): return root * 2 + 1 def right_child(self, root): return root * 2 + 2 def father(self, node): return (node - 1) // 2 def heapify(self, root): if root > self.size() - 1: return left_node = self.left_child(root) right_node = self.right_child(root) largest = root if left_node <= self.size() - 1: if self.data_list[left_node] > self.data_list[largest]: largest = left_node if right_node <= self.size() - 1: if self.data_list[right_node] > self.data_list[largest]: largest = right_node if largest != root: self.data_list[root], self.data_list[largest] = self.data_list[largest], self.data_list[root] self.heapify(largest) def build_heap(self, dl): for i in range(len(dl) - 1, -1, -1): self.insert(dl[i]) def get_max(self): if self.size() == 0: return None ret = self.data_list[0] self.data_list[0] = self.data_list[-1] del self.data_list[-1] self.heapify(0) return ret def insert(self, data): self.data_list.append(data) now_index = self.size() - 1 pre = self.father(now_index) while now_index != 0 and self.data_list[pre] < data: self.data_list[pre], self.data_list[now_index] = self.data_list[now_index], self.data_list[pre] now_index = pre pre = now_index // 2 heap = Heap() heap.insert(9) heap.insert(10) heap.insert(7) heap.insert(12) heap.insert(3) heap.insert(4) print(heap.get_max()) print(heap.get_max()) print(heap.get_max()) print(heap.get_max()) print(heap.get_max()) print(heap.get_max()) print('-' * 100) heap.insert(10) heap.insert(9) heap.insert(8) heap.insert(7) heap.insert(7) heap.insert(12) print(heap.get_max()) print('-' * 100) heap1 = Heap() data_list = [1, 2, 3, 4, 5, 6, 7] heap1.build_heap(data_list) print(heap1.get_max())
输出结果:
/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Users/baoshan/PycharmProjects/myProject/python_weixin_study/heap.py 12 10 9 7 4 3 ---------------------------------------------------------------------------------------------------- 12 ---------------------------------------------------------------------------------------------------- 7 Process finished with exit code 0
请大侠们指教!