# -*- coding: utf-8 -*-
"""
Created on Fri Jul 5 10:13:16 2019
@author: Yuki
"""
def heapAdjust(nums, Len, index):
left = index*2 + 1
right = index*2 + 2
maxIndex = index
if left<Len and nums[left] > nums[maxIndex]:
maxIndex = left
if right < Len and nums[right]>nums[maxIndex]:
maxIndex = right
if maxIndex != index:
nums[index], nums[maxIndex] = nums[maxIndex], nums[index]
heapAdjust(nums, Len, maxIndex)
def heapSort(nums):
Len = len(nums)
#构建大根堆(从最后一个非叶子节点向上)
for i in range(Len//2-1, -1, -1):
heapAdjust(nums, Len, i)
for i in range(len(nums)-1, 0, -1):
nums[0], nums[i] = nums[i], nums[0] # 将当前最大的放置到数组末尾
heapAdjust(nums, i, 0) # 将未完成排序的部分继续进行堆排序
return nums
nums = [100,20,5,40,888,432,-100,-5]
res = heapSort(nums)