# -*- coding=utf-8 -*-
def MaxHeapify(li, i):
'''本函数的功能是在数组li中,使下标为i对应的值遵循最大堆的性质
即它的子女必须小于等于它,以此类推,直到这个值满足条件或者它在
叶子节点上'''
l = 2 * i +1
r = 2 * i +2
largest = i
if l < len(li) and li[l] > li[i]:
largest = l
if r < len(li) and li[r] > li[largest]:
largest = r
if largest != i:
li[i], li[largest] = li[largest], li[i]
MaxHeapify(li, largest)
def BuildMaxHeap(li):
'''本函数的功能是使数组li对应的堆变为最大堆'''
i = len(li)/2 - 1
while i >= 0:
MaxHeapify(li, i)
i -= 1
def HeapSort(li):
'''本函数的功能是实现堆排序'''
BuildMaxHeap(li)
print li,'\n----------------------------------'
i = len(li) - 1
while i >= 1:
li[i],li[0] = li[0],li[i]
tmp = li[:i]
MaxHeapify(tmp,0)
li[:i] = tmp
print li
i -= 1
if __name__ == '__main__':
li = [5,14,2,25,7,17,20,8,4]
HeapSort(li)
print li