最小(大)堆是按完全二叉树的排序顺序的方式排布堆中元素的,并且满足:ai >a(2i+1) and ai>a(2i+2)( ai <a(2i+1) and ai<a(2i+2)).堆是一种高级的数据结构,在Python中,有相应的模块deapq。
下面给出自己编写的代码实现最小堆与使用heapq模块实现最小堆作一个对比:
#定义Myheap类
import heapq as p import random class MyHeap(object): def __init__(self,arr=[]): self.n=len(arr) self.list=arr def creat_heap(self): p.heapify(self.list) #建堆 return self.list def creat_heap1(self): parent_num=(self.n-1)/2 while 0<=parent_num: self.siftdown(parent_num) parent_num-=1 return self.list def siftdown(self,parent_num): i=parent_num j=2*parent_num+1 temp=self.list[parent_num] while j<self.n : if j<self.n-1 and self.list[j+1]<self.list[j] : j=j+1 if temp<=self.list[j]: break else: self.list[i]=self.list[j] i=j j=2*i+1 self.list[i]=temp def heap_sort(self): #堆排序 b=[] for i in xrange(self.n): p.heapify(self.list) b.append(p.heappop(self.list)) return b
测试:
1 a1=[random.randint(1,100) for i in xrange(10)] 2 print a1 3 myheap1=MyHeap(a1) 4 myheap2=MyHeap(a1) 5 print myheap1.creat_heap() 6 print myheap2.creat_heap1() 7 print myheap1.heap_sort()
结果:
[86, 44, 34, 10, 85, 30, 62, 60, 53, 21]
[10, 21, 30, 44, 85, 34, 62, 60, 53, 86]
[10, 21, 30, 44, 85, 34, 62, 60, 53, 86]