array = [0,30,20,80,40,50,10,60,70,90] # 待排序序列 # i = 4-1 或 1 # n = len(array) total = len(array) - 1 # 调整为大顶堆,i是指从哪个结点开始调整,n代表待排序元素总数 def adjust_heap(n,i,array): #length = len(array) #print_tree(array) while i * 2 <= n: lchild_index = 2 * i max_child_index = lchild_index if n > lchild_index and array[lchild_index + 1] > array[lchild_index]: max_child_index = lchild_index + 1 if array[max_child_index] > array[i]: array[max_child_index],array[i] = array[i],array[max_child_index] i = max_child_index else: break # 选择从哪个结点开始排序 for i in range(4,0,-1): adjust_heap(len(array)-1,i,array) # 选择排序实现 def sort(total,array): while total > 1: array[1],array[total] = array[total],array[1] total -= 1 # 特殊情况,当只剩两元素时,直接比较,不用调整 if total == 2 and array[1] < array[total]: break adjust_heap(total,1,array) return array sort(total,array)
本文出自 “12064120” 博客,请务必保留此出处http://12074120.blog.51cto.com/12064120/1976141
原文:http://12074120.blog.51cto.com/12064120/1976141