主要步骤:
- 将无需序列构建成一个堆,根据升序降序需求选择大顶堆或小顶堆;
- 将堆顶元素与末尾元素交换,将最大元素"沉"到数组末端; 重新调整结构,使其满足堆定义,然后继续交换堆顶元素与当前末尾元素,反复执行调整+交换步骤,直到堆为空(即堆的每个元素被交换)。
图解步骤参考博客
参考视频讲解
# 堆排序
# 1 首先构建一个堆
# 1.1 使用heapify函数对堆中的某一个元素进行微调,使之再次成为堆
def heapify(sequences, n, i):
if(i >= n):
return
max = i
lchild = 2*i+1
rchild = 2*i+2
if lchild<n and sequences[lchild] > sequences[max]:
max = lchild
if rchild<n and sequences[rchild] > sequences[max]:
max = rchild
if max != i:
sequences[i], sequences[max] = sequences[max], sequences[i]
heapify(sequences, n, max)
# 1.2 使用heapify函数从最后一个非叶子节点到根节点进行调整,使用无序元素构建成一个堆
def build_heap(sequences):
#建立一个堆
first_adjust_node = len(sequences) // 2
for i in range(first_adjust_node, -1, -1):
heapify(sequences, len(sequences), i)
# 2 对已经建立的堆进行以下反复调整:每次将大头堆堆顶元素和顶尾元素互换(即将最大元素一刀堆尾部),然后将堆尾部元素去除出堆,对剩下的堆顶元素进行heapify操作使之成为新的堆,反复执行上述操作直到最后堆为空
def heap_sort(sequences):
# 首先对无序序列构建一个有序堆
build_heap(sequences)
# 然后依次将堆顶元素 和 堆尾部 元素呼唤,将堆的尾部节点去掉,并且对对顶元素进行heap操作
for i in range(len(sequences)-1, -1, -1):
sequences[0], sequences[i] = sequences[i], sequences[0]
heapify(sequences, i, 0)
return sequences
seq = [31, 26, 15, 10, 4, 13, 14, 18, 25]
print(seq)