#-*- 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)