Python -堆的實現

     最小(大)堆是按徹底二叉樹的排序順序的方式排布堆中元素的,而且知足:ai  >a(2i+1)  and ai>a(2i+2)( a <a(2i+1)  and ai<a(2i+2)).堆是一種高級的數據結構,在Python中,有相應的模塊deapq。api

下面給出本身編寫的代碼實現最小堆與使用heapq模塊實現最小堆做一個對比:數據結構

#定義Myheap類app

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
        

測試:dom

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]spa

相關文章
相關標籤/搜索