基础知识
- 堆是一个完全二叉树的数据结构
- 用数组表示完全二叉树时(按层次遍历的次序存储),下标为i的节点,其左右子节点为2*i、2*i+1
- 为方便计算,0下标的位置不存储数据
堆排序过程(以大顶堆为例)
- 将数组构建成大顶堆---根节点为最大值
- 将根节点与最后一个节点位置n交换
- 将前n-1个节点重新构建大顶堆
- 重复上述步骤,直到剩下n-(n-1)个节点,排序完成
def heap_sort(nums):
nums_copy = [0]
nums_copy.extend(nums)
do_heap_sort(nums_copy)
nums_copy.pop(0)
return nums_copy
def do_heap_sort(nums):
length = len(nums)
start_index = (length-1)/2
for i in range(start_index, 0, -1):
heap_adjust(nums, i, length-1)
for i in range(1, length-1):
nums[1], nums[length-i] = nums[length-i], nums[1]
heap_adjust(nums, 1, length-i-1)
def heap_adjust(nums, start, end):
temp = nums[start]
i = start * 2
while i <= end:
if i < end and nums[i] < nums[i+1]:
i += 1
if nums[i] > temp:
nums[start] = nums[i]
start = i
i *= 2
else:
break
nums[start] = temp
print heap_sort([50, 16, 30, 10, 60, 90, 2, 80, 70])
- heap_sort函数对外提供,接收一个乱序数组作为参数,并将数组整体往后挪一位