#堆heap
class heap(object):
def __init__(self):
self.data_list = []
def get_parent_index(self,index):
if index==0 or index>len(self.data_list)-1:
return None
else:
return (index-1)//2
def swap(self,index_a,index_b):
self.data_list[index_a],self.data_list[index_b] = self.data_list[index_b],self.data_list[index_a]
def insert(self,data):
self.data_list.append(data)
index = len(self.data_list)-1
parent = self.get_parent_index(index)
while parent is not None and self.data_list[parent] < self.data_list[index]:
self.swap(parent,index)
index = parent
parent = self.get_parent_index(parent)
def remove_max(self):
remove_data = self.data_list[0]
self.data_list[0] = self.data_list[-1]
del self.data_list[-1]
self.max_heapify(0)
return remove_data
def max_heapify(self,index):
total_index = len(self.data_list) - 1
while True:
maxvalue_index = index
if 2*index+1<=total_index and self.data_list[2*index+1]>self.data_list[maxvalue_index]:
maxvalue_index = 2*index + 1
if 2*index+2<=total_index and self.data_list[2*index+2]>self.data_list[maxvalue_index]:
maxvalue_index = 2 * index + 2
if maxvalue_index == index:
break
self.swap(index, maxvalue_index)
index = maxvalue_index
def heap_sort(self):
sort_lst = []
for i in range(len(self.data_list)):
_max = self.remove_max()
sort_lst.append(_max)
return sort_lst[::-1]
if __name__ == '__main__':
lst = [1,5,7,2,10]
heap = heap()
for i in lst:
heap.insert(i)
print(heap.data_list)
print(heap.heap_sort())
python实现堆和堆排序
最新推荐文章于 2022-05-23 10:52:02 发布