堆排序是一种选择排序。
选择排序:每趟从待排序的记录中选出关键字最小的记录,顺序放在已排序的记录序列末尾,直到全部排序结束为止。
def HeadSort(input_list):
def HeadAdjust(input_list,parent,length):
temp=input_list[parent]
child=2*parent+1
while child<length:
if child+1<length and input_list[child]<input_list[child+1]:
child+=1
if temp>=input_list[child]:
break
input_list[parent]=input_list[child]
parent=child
child=2*parent+1
input_list[parent]=temp
if len(input_list)==0:
return []
sorted_list=input_list
length=len(sorted_list)
for i in range(0,length//2)[::-1]:
HeadAdjust(sorted_list,i,length)
for j in range(1,length)[::-1]:
sorted_list[j],sorted_list[0]=sorted_list[0],sorted_list[j]
HeadAdjust(sorted_list,0,j)
print ("第%d趟排序:"%(length-j),end ='')
print(sorted_list)
return sorted_list
if __name__ == "__main__":
input_list=[6,4,8,9,2,3,1]
print('排序前:',input_list)
sorted_list=HeadSort(input_list)
print('排序后:',sorted_list)
排序前: [6, 4, 8, 9, 2, 3, 1]
第1趟排序:[8, 6, 3, 4, 2, 1, 9]
第2趟排序:[6, 4, 3, 1, 2, 8, 9]
第3趟排序:[4, 2, 3, 1, 6, 8, 9]
第4趟排序:[3, 2, 1, 4, 6, 8, 9]
第5趟排序:[2, 1, 3, 4, 6, 8, 9]
第6趟排序:[1, 2, 3, 4, 6, 8, 9]
排序前: [1, 2, 3, 4, 6, 8, 9]
(1)根据初始数组去构造初始堆(构建一个完全二叉树,保证所有的父结点都比它的孩子结点数值大)。
(2)每次交换第一个和最后一个元素,输出最后一个元素(最大值),然后把剩下元素重新调整为大根堆。