堆排序(以大根堆为例)
向下调整
def sift(li,low,high):
"""
:param li: 列表
:param low: 堆的根节点位置
:param high: 堆的最后一个元素位置
:return:
"""
i = low
j = 2 * i + 1
tmp = li[low]
while j <= high:
if j + 1 <= high and li[j + 1] > li[j]:
j = j + 1
if li[j] > tmp:
li[i] = li[j]
i = j
j = 2 * i + 1
else:
break
li[i] = tmp
堆排序
def heap_sort(li):
n = len(li)
for i in range((n - 2) // 2,-1,-1):
sift(li,i,n - 1)
for i in range(n - 1,-1,-1):
li[0],li[i] = li[i],li[0]
sift(li,0,i - 1)
验证
import random
li = [i for i in range(1,11)]
random.shuffle(li)
print(li)
heap_sort(li)
print(li)