大顶堆
def swap(L, i, j):
L[i], L[j] = L[j], L[i]
def HeapAdjust(L, parent, length):
j = 2 * parent
tmp = L[parent]
while j <= length:
if j < length and L[j] < L[j+1]:# L[j] > L[j+1] 小顶堆
j += 1
if tmp > L[j]:#<小顶堆
break
L[parent] = L[j]
parent = j
j *= 2
L[parent] = tmp
def HeapSort(L):
length = len(L) - 1
start = (length) // 2
for i in range(start, 0, -1):
HeapAdjust(L, i, length)
for i in range(length, 1, -1):
swap(L, 1, i)
HeapAdjust(L, 1, i-1)
L = [3, 6, 7, 8, 1, 4, 2, 5, 9]
print(L)
L.insert(0, 0)
HeapSort(L)
L.pop(0)
print(L)
output:
[3, 6, 7, 8, 1, 4, 2, 5, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
习惯从下标1开始排序,但是计算机存储从下标0开始