# 交换
def swap(a, x, y):
t = a[x]
a[x] = a[y]
a[y] = t
# 寻找根节点
def heapify(a, n, i):
c1 = 2 * i + 1
c2 = 2 * i + 2
max = i
#找到根节点和它的两个子结点的并移动到根节点
if c1 < n and a[c1] > a[max]:
max = c1
if c2 < n and a[c2] > a[max]:
max = c2
if max != i:
swap(a, max, i)
heapify(a, n, max)
# 创建堆
def build_heap(a, n):
last_node = n - 1
parent = int((last_node - 1) / 2)
#从最后一个节点开始创建大根堆
for i in range(parent, -1,-1):
heapify(a, n, i)
# 实现堆排序
def heap_sort(a,n):
#创建堆
build_heap(a,n)
for i in range(n-1,-1,-1):
#将最大堆排到末尾
swap(a,0,i)
#从未排序堆中找出最大数
heapify(a,i,0)
arr = [9, 4, 5, 3, 8, 1]
heap_sort(arr, len(arr))
print(arr)