Python -堆的實現


     最小(大)堆是按完全二叉樹的排序順序的方式排布堆中元素的,並且滿足:ai  >a(2i+1)  and ai>a(2i+2)( a <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]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM