用Python实现大顶堆
来源:互联网 发布:哪个软件下载最快 编辑:程序博客网 时间:2024/06/01 18:25
#!/usr/bin/env python2# -*- coding: utf-8 -*-"""Created on Wed May 10 18:52:57 2017@author: zz"""class MaxHeap: def __init__(self, data): data.insert(0, None) self.heap = data self.heapSize = 0 for i in range(1,len(self.heap)): self.heapSize += 1 self.__bubble(i) def __sink(self, pos): left, right = 2*pos, 2*pos+1 next = pos if left <= self.heapSize and self.compare(self.heap[left], self.heap[next]) > 0: next = left if right <= self.heapSize and self.compare(self.heap[right], self.heap[next]) > 0: next = right if next == pos: return self.__exchange(pos, next) return self.__sink(next) def __bubble(self, pos): # build if pos <= 1: return ppos = pos/2 if self.compare(self.heap[pos], self.heap[ppos]) > 0: self.__exchange(pos, ppos) return self.__bubble(ppos) def compare(self, a, b): return a - b def __exchange(self, i, j): temp = self.heap[i] self.heap[i] = self.heap[j] self.heap[j] = temp def sort(self): while self.heapSize > 1: self.__exchange(1, self.heapSize) self.heapSize -= 1 self.__sink(1) self.heap.remove(None) return self.heapmaxHeap = MaxHeap([4, 5, 7, 7, 1, 3, 8, -1])print maxHeap.sort()
运行结果
[-1, 1, 3, 4, 5, 7, 7, 8]
0 0
- 用Python实现大顶堆
- 用Python实现ORM
- 用Python实现Spy++
- 用Python实现栈
- 用Python实现队列
- 用Python实现Spy++
- 用python实现二项树
- 用Python实现ROT13
- BLAST-用python实现
- 用python实现排列
- 用 python 实现批处理文件
- 用python实现单链表
- 用 Python 实现 LDA
- 用python实现数组
- 用python实现排列组合
- 用Python实现BubbleSort
- [Python]用Python实现Web自动测试
- pypy -- 用python实现的python
- Linux文件(区域)锁函数 -- open()、fcntl()
- 手机卫士day07
- Another resource already exists with name
- 关于使用2d照片进行3d建模
- Lambda表达式
- 用Python实现大顶堆
- Linux系统统计函数时间
- sql语句中各子部分的执行顺序
- 龙芯平台上构建Go语言环境指南
- Zookeeper系列(十三)Zookeeper开源客户端之Curator的事件监听丢失分析
- linux修改语言环境为中文
- OpenGL绘制教室,带你亲手编程浅识高大上的VR技术
- 关于打不开DDMS中data文件夹的问题
- 手机卫士day08