class minHeap(object):
def __init__(self,list):
self.list = list
self.length = len(list)
def shiftdown(self, index):
flag=False
while index*2 < self.length and flag==False:
#首先处理左子树
if self.list[index] > self.list[index*2]:
t = index*2
else:
t = index
#再看看是否存在右子树
if index*2+1 < self.length:
if self.list[t] > self.list[index*2+1]:
t = index*2+1
if t!=index:
self.swap(index,t)
index=t
else:
flag=1
def swap(self,child_index,parent_index):
temp = self.list[child_index]
self.list[child_index] = self.list[parent_index]
self.list[parent_index] = temp
def built_heap(self):
index = int(len(self.list)/2)
while index>0:
self.shiftdown(in
python 利用list实现HeapSort(小顶堆)
最新推荐文章于 2024-01-19 12:20:15 发布