def heap_sort(ary):
n = len(ary) #
first = int(n / 2 - 1) #
for start in range(first, -1, -1): # 3~0 revese
max_heapify(ary, start, n - 1) # from start
for end in range(n - 1, 0, -1):
ary[end], ary[0] = ary[0], ary[end]
max_heapify(ary, 0, end - 1)
return ary def max_heapify(ary, start, end):
root = start
while True:
child = root * 2 + 1
if child > end:
break
if child + 1 <= end and ary[child] < ary[child + 1]:
child += 1
if ary[root] < ary[child]:
ary[root], ary[child] = ary[child], ary[root]
root = child
else:
break def main():
ary = [6, 5, 3, 1, 8, 7, 2, 4]
heap_sort(ary) print(ary) main()
//Py自带的两种算法,一个sorted(ary)不影响本身结构,可ary.sort()就影响了
def main():
# ary = [6, 5, 3, 1, 8, 7, 2, 4]
#heap_sort(ary) #print(ary) n = int(sys.stdin.readline())
ary = [] # 申明一个数组 while n > 0:
ary.append(int(raw_input())) # 输入的排成数组
n -= 1 ary.sort() #自带两种排序算法,.sort是真是变,sorter()是表面变
print '\n'.join(map(str, ary)) # map函数就是一个映射/转换,把list转换成string main()
学习
挑战了一把当年讳莫如深的堆排,现在理解其实不难,就是一个使用二叉来减少比较次数的快速排序
各种py排序算法
http://wuchong.me/blog/2014/02/09/algorithm-sort-summary/
熟悉了通过查看文档来学习使用python的相关函数
熟悉调用其自生的函数库