堆python_堆(python)

#-*- coding:utf-8 -*-

classArray(object):def __init__(self, size=32):

self._size=size

self._items= [None] *sizedef __getitem__(self, index):returnself._items[index]def __setitem__(self, index, value):

self._items[index]=valuedef __len__(self):returnself._sizedef clear(self, value=None):for i inrange(len(self._items)):

self._items[i]=valuedef __iter__(self):for item inself._items:yielditemclassMaxHeap(object):def __init__(self, maxsize=None):

self.maxsize=maxsize

self._elements=Array(maxsize)

self._count=0def __len__(self):returnself._countdefadd(self, value):if self._count >=self.maxsize:raise Exception(‘full‘)

self._elements[self._count]=value

self._count+= 1self._siftup(self._count-1)def_siftup(self, ndx):if ndx >0:

parent= int((ndx-1)/2)if self._elements[ndx] >self._elements[parent]:

self._elements[ndx], self._elements[parent]=self._elements[parent], self._elements[ndx]

self._siftup(parent)defextract(self):if self._count <=0:raise Exception(‘empty‘)

value=self._elements[0]

self._count-= 1self._elements[0]=self._elements[self._count]

self._siftdown(0)returnvaluedef_siftdown(self, ndx):

left= 2 * ndx + 1right= 2 * ndx + 2

#determine which node contains the larger value

largest =ndxif (left < self._count and #有左孩子

self._elements[left] >= self._elements[largest] andself._elements[left]>= self._elements[right]): #原书这个地方没写实际上找的未必是largest

largest =leftelif right < self._count and self._elements[right] >=self._elements[largest]:

largest=rightif largest !=ndx:

self._elements[ndx], self._elements[largest]=self._elements[largest], self._elements[ndx]

self._siftdown(largest)deftest_maxheap():importrandom

n= 5h=MaxHeap(n)for i inrange(n):

h.add(i)for i inreversed(range(n)):assert i ==h.extract()defheapsort_reverse(array):

length=len(array)

maxheap=MaxHeap(length)for i inarray:

maxheap.add(i)

res=[]for i inrange(length):

res.append(maxheap.extract())returnresdeftest_heapsort_reverse():importrandom

l= list(range(10))

random.shuffle(l)assert heapsort_reverse(l) == sorted(l, reverse=True)defheapsort_use_heapq(iterable):from heapq importheappush, heappop

items=[]for value initerable:

heappush(items, value)return [heappop(items) for i inrange(len(items))]deftest_heapsort_use_heapq():importrandom

l= list(range(10))

random.shuffle(l)assert heapsort_use_heapq(l) == sorted(l)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值