标签:
from functools import reduce
def swap(a, i, j):
t = a[i]
a[i]=a[j]
a[j]=t
def heapify_sub_tree1(a,i,size):
minimum = i
j = 2*i
if (j<=size and a[j] < a[minimum]):
minimum = j
if (j+1 <= size) and (a[j+1] < a[minimum]):
minimum = j + 1
swap(a, minimum, i)
if minimum != i:
print ("i")
print (i)
print ("minimum")
print (minimum)
heapify_sub_tree1(a, minimum, size)
def heap(a,size):
i = size//2
while(i > 0):
heapify_sub_tree1(a, i, size)
print (i)
i = i-1
def adjust_tree(a, e):
i = len(a)-1
while(e < a[i//2]):
a[i] = a[i//2]
i = i//2
a[i] = e
def insert(a, e):
a.append(e)
adjust_tree(a,e)
def heap_sort(a):
size = len(a)-1
while(size>1):
swap(a, 1, size)
size = size-1
heap(a, size)
a=[10,88,2,9,51]
heap(a, len(a)-1)
print (a)
insert(a,4)
print (a)
insert(a,11)
print (a)
insert(a,7)
print (a)
heap_sort(a)
print (a)
Division and Recursion-HeapSort
标签:
原文地址:http://www.cnblogs.com/zhaodonglin/p/5401180.html