代码
def heapSort(alist):
heap = [0]
heap.extend(alist) # 直接将列表入堆,这样叶子节点就不需要下沉
heapSize = len(alist)
i = heapSize // 2 # 下沉的顺序必须是从底部到顶部
while i > 0: # 构建有序二叉堆
sink(i, heap, heapSize)
i = i - 1
for i in range(len(alist)):
alist[i] = delMin(heap, heapSize)
heapSize = heapSize - 1 # 堆中元素不断减小,堆得大小也需要不断更新
def sink(index, heap, heapSize): # 将index位置的元素沉底
# print(heap)
while index*2 <= heapSize: # 保证不是叶子节点
mi = getMin(index, heap, heapSize) # 得到小儿子的索引
if heap[index] > heap[mi]:
heap[index], heap[mi] =
heap[mi], heap[index]
index = mi
else:
break # 如果父亲比两个儿子都小,循环停止
def getMin(index, heap, heapSize): # 得到小儿子的索引
if index*2+1 > heapSize:
return index*2
else:
if heap[index*2] < heap[index*2+1]:
return index*2
else:
return index*2+1
def delMin(heap, heapSize): # 去顶+重构有序二叉堆
temp = heap[1] # 记录即将遗失的变量(返回需要用到)
heap[1] = heap[heapSize] # 将尾部节点移至堆顶,准备下沉
heap.pop()
sink(1, heap, heapSize-1) # 下沉堆顶元素
return temp
l1 = [5, 2, 0, 1, 3, 1, 4]
heapSort(l1)
print(l1)
体会
用函数的方法实现堆排序,由于需要调用多个函数,而且调用的函数需要多个参数,不如用类的方法简洁