# -*- coding:utf-8 -*-
def head_sort(list):
length_list = len(list)
first=int(length_list/2-1)
# 假设 len=8, 这里 first=3, 下面的 range 就是[3210]
for start in range(first,-1,-1): # 循环把所有子树生成大根堆
max_heapify(list,start,length_list-1)
for end in range(length_list-1,0,-1):
list[end],list[0]=list[0],list[end]
max_heapify(list,0,end-1) # 后面就是自上而下的交换了,不用每个都判断了(不用像生成大根堆那样)
return list
def max_heapify(ary,start,end): # 把子树生成大根堆
root = start
# 其中标*的两句话是为什么结点到上面的几层仍然可以与底层的进行比较交换的原因
while True: # *
child = root*2 + 1
if child > end: # 判断是否有左孩子
break
if child + 1 <= end and ary[child]<ary[child+1]: # 判断是否有右孩子,且如有就留大的
child = child + 1
if ary[root]<ary[child]: # 把刚那个大的孩子与根进行比较交换
ary[root],ary[child]=ary[child],ary[root]
root=child # *
else:
break
#测试:
list=[10,23,1,53,654,54,16,646,65,3155,546,31]
print head_sort(list)